7

I currently have a NodeJS application with an Express backend and all the frontend implemented with EJS. An example route looks like this currently:

router.get("/:name&:term", function(req, res) {
    Course.find({ courseName: req.params.name, courseTerm: req.params.term }).populate("students")
    .exec(function(err, foundCourse) {
        if (err) {
            console.log(err);
        } else {
            console.log(foundCourse)
            res.render("courses/show", { course: foundCourse });        
        }
    });
});

I have a lot of the pages of the website already implemented following the example route above. So the structure looks something like:

localhost:3000
-/courses
   -/show
   -/review
-/professors
   -/show
   -/rating
...

But I recently took a React course and want to use React for new pages like localhost:3000/groups

Is there a way to use React for some pages and still have EJS pages that I currently have? or do I have to rewrite all the EJS pages to React components? I'm still very new to web dev so any advice would be highly appreciated.

From my understanding, I would have to let the React app catch only certain requests/routes but I am not quite sure how to do that.

2
  • 1
    So you want to use the Express router alongside with the React router? Or just sprinkle in some React components in some Express routes? Commented Aug 16, 2020 at 9:08
  • 1
    yes, ideally I would like to use the Express router with the React router. I would also like to know how to add some React components in the existing Express routes as well:) Commented Aug 16, 2020 at 10:06

3 Answers 3

3
+25

To answer this question thoroughly I'd have to write a small book, so I only show a basic case where the code is rendered client-side. I also assume that you know how to transpile jsx to js, so I'll treat all react files as already transpiled (that is all <> are converted to React.createElement()).

First, you have to create a route that will be handled by react (/groups), (I assume that you'll use some data for the rendering as in your example):

router.get("groups/:name&:term", function(req, res) {
    Groups.find({ groupName: req.params.name, courseTerm: req.params.term }).populate("students")
    .exec(function(err, foundGroup) {
        if (err) {
            console.log(err);
        } else {
            // here will be the react rendering code        
        }
    });
});

Assuming that you have react code in index.js, you have to add it to the html code as well as data required by the app:

router.get("groups/:name&:term", function(req, res) {
    Groups.find({ groupName: req.params.name, courseTerm: req.params.term }).populate("students")
    .exec(function(err, foundGroup) {
        if (err) {
            console.log(err);
        } else {
            res.send(`<html>
               <head>
                 <script>
                   const initialData=${JSON.stringify(foundGroup)};
                 </script>
               </head>
               <body>
                 <div id="react-root"></div>
                 <script src="index.js"></script>
               </body>
            </html>`);
                    
        }
    });
});

Your App should consume the data like this:

React.render(<App initialData={initialData}/>, document.getElementById("react-root");

This should get your react code up and running. Going further, you can use react-dom/server to prerender html on the server, and mix-in ejs file as a template in which you inject react code to utilize your existing codebase.

Sign up to request clarification or add additional context in comments.

10 Comments

Could I have something like res.json(foundGroup) under the else statement and use componentDidMount and fetch in the React component and use react-router in App.js file to render the Component for /groups routes? If so, how can I do it with hooks?
@ph-quiett yes, you can fetch the data after the app is rendered, but it would be a waste of the user's time - it would require 2 round trips: first for the page and then the second one for the data after the app is ready.
ah I see, then how would a typical express-react code look like that require only 1 trip instead of 2?
@ph-quiett if the app needs some data from the server for the actual route, it gathers the data and places it in a global variable, ie initialData which is then consumed by the app on the initial render.
is that done using redux? I would really appreciate it if you could provide a sample code <3
|
1

Is there a way to use React for some pages and still have EJS pages that I currently have?

Yes you can, react is just javascript.

You can use create-react-app for a single page and serve that from the route of your choice but keep in mind that your front-end won't become a SPA by doing this you'll just be serving a react app on a certain route.

A somewhat better approach would be to not use create-react-app and instead setup your custom webpack build process to convert jsx to javascript, write a minimal ejs template to include your transpiled javascript code into the HTML, and serve that template from a route.

Comments

-1

Reactjs component can be part of your backend code when using SSR(server side rendering) which is much more complicated. Or you can use a express static server to serve reactjs app which is ready to deploy, then express will only be a simple the static file router.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.