I'm very confused about mixing express routes with React and .jsx files. I'm trying to build a multipage website with a mongoose database and I've been using ejs to do it. now I'm trying to convert to React but I have absolutely no idea of how to do this despite my research for 3 days. What I'm looking to do is roughly something like this (example is a react component "example.jsx")
app.get("/",function(req,res){ res.send(<example />)})
instead of
app.get("/",function(req,res){ res.send("another.ejs") })
If I cant do such a thing would you recommend React routs or just sticking with ejs.
You need to (1.) convert the JSX code to Javascript, and then (2.) render the Javascript into an HTML string, which you then can send to the client.
E.g. if you have the file example.js:
console.log('jsxData:', <example />);
// app.get("/",function(req,res){ res.send(<example />)})
If a Javascript file contains JSX code, it becomes a JSX file, and Javascript can't understand it anymore. The extension .js or .jsx doesn't matter here. You may or may not rename it to example.jsx, if you like.
But you can convert (aka. "transpile") that JSX file into a Javascript file with babel. You will get a new, separate file which is a valid Javascript file.
1.a. If it's not already installed, you need to install babel and the JSX transpiler (For the installation I'm using yarn here, npm is also possible):
yarn add @babel/cli @babel/core @babel/preset-react --dev
1.b. Convert the JSX file to Javascript:
yarn babel example.js --presets=@babel/preset-react --out-dir dist
Now you should have the new file /dist/example.js, which is a valid Javascript file (but still not an HTML file). (The extension of this file will be .js, not matter if the original source file was .js or .jsx.)
In step 1. you have transpiled the JSX code <example /> inside your original file into the Javascript code React.createElement("example", null) inside the transpiled file, but this is still not HTML, this is a Javascript "React element".
You can use ReactDOMServer to render this React element into HTML:
2.a. In case it's not already installed, then install react and react-dom:
yarn add react react-dom
2.b. Import react and react-dom/server, and use the renderToString() method to render the React element into an HTML string:
const React = require('react'); // <-- React is required, because it is used in the transpiled .js file.
const ReactDOMServer = require('react-dom/server');
const jsxData = <example />;
const htmlString = ReactDOMServer.renderToString( jsxData );
console.log('htmlString:', htmlString);
// app.get("/",function(req,res){ res.send( htmlString )})
Transpile this JSX file again as before. Now inside the ./dist/example.js the htmlString should contain the HTML string which you can send to the client. In this example, if you run e.g. node ./dist/example.js you should see the console output:
htmlString: <example data-reactroot=""></example>