I am trying to wire up a minimum proof-of-concept to render a single React component server-side.
When I run my app, I get an error:
SyntaxError: express.js: Unexpected token (10:41)
And the offending line is:
> 10 | res.send(ReactDOMServer.renderToString(<Component msg={msg} />));
| ^
This is my package.json
:
{
"name": "ssrReact",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "nodemon express.js --exec babel-node --presets es2015,stage-2"
},
"dependencies": {
"express": "^4.14.1",
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"babel-cli": "^6.22.2",
"babel-preset-es2015": "^6.22.0",
"babel-preset-stage-2": "^6.22.0",
"nodemon": "^1.11.0"
}
}
This is my Component.js
:
import React from 'react';
class Component extends React.Component {
render() {
return <h1>Hello, {this.props.msg}</h1>;
}
}
export default Component;
This is my express.js
:
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Component from './Component';
const app = express();
function home (req, res) {
const msg = req.params.msg || 'Hello';
res.send(ReactDOMServer.renderToString(<Component msg={msg} />));
}
app.get('/', home);
app.get('/:msg', home);
app.listen(3333);
What do I need to change in order to allow Express to serve a React component?
Thanks for the help.
On the server side, we use express to define a root endpoint which serves a index. html file. When a request is received, we render our React app root component App to a string using ReactDOMServer. renderToString .
Yes! This is where server-side rendering for React comes in. In this article, I want to introduce you to server-side rending (SSR) with React, reasons to use it, and some popular frameworks for rendering React on the server side.
Client-Side Rendering By default, your React app will be client-side rendered. This means basically, all of the source code will live in JavaScript files referenced in a single HTML file that initializes your app.
My two cents, do:
npm i -D babel-preset-react
And change your running script to:
"scripts": {
"start": "nodemon express.js --exec babel-node --presets es2015,stage-2,react"
},
To parse jsx you need to install the babel-preset-react
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With