Reputation: 71
How we can convert client-side rendering react js app to server-side rendering using react-router 4?
Upvotes: 7
Views: 11603
Reputation: 284
Assuming you are using Create React App with React Router 4, you'll need to do the following steps:
root/server/index.jsx
that contains your Express server, serving the default setup of CRA as documented here: https://create-react-app.dev/docs/deployment#other-solutionssrc/App.jsx
component in your server/index.jsx
, use ReactDOMServer.renderToString(<App/>)
to render your app to a string, then inject it into the build/index.html
, and res.send the injected HTML to the browser upon a request.node server/index.jsx
does not work because node does not understand JSX. You'll need to setup webpack with babel to transpile your server/index.jsx
, and then run the transpiled file with node. Because your server code imports src/App.jsx
, which may also import css, svg, png, jpg, etc.
files, you'll get a lot of errors running your server. Fix errors one by one by configuring your webpack to suit your use cases.src/index.js
to use ReactDOM.hydrate() instead of ReactDOM.render().src/index.js
, but in server/index.js
on server-side, use StaticRouter instead and pass req.originalUrl to that StaticRouter. This is because BrowserRouter read address from your browser address bar, but the server does not have an address bar.Recommendations if you want to add SSR for CRA:
Upvotes: 8