How we can convert client-side rendering react js app to server-side rendering using react-router 4?
How we can convert client side rendering react js app to server side rendering using react router 4?
Asked Answered
Assuming you are using Create React App with React Router 4, you'll need to do the following steps:
- Create an SSR server: Add a
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-solutions - Render your app on server: Import your
src/App.jsx
component in yourserver/index.jsx
, useReactDOMServer.renderToString(<App/>)
to render your app to a string, then inject it into thebuild/index.html
, and res.send the injected HTML to the browser upon a request. - Try to run your server:
node server/index.jsx
does not work because node does not understand JSX. You'll need to setup webpack with babel to transpile yourserver/index.jsx
, and then run the transpiled file with node. Because your server code importssrc/App.jsx
, which may also importcss, 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. - Hydrate your app on client: After successfully running your server, try to send a request from a browser. You may see a blank page but don't worry because we have not rendered correctly on the server yet. However, let's assume that your server did render something on step 2 above. Then, when your browser receives the HTML page, it just needs to make interactive components like buttons work properly. To do this, edit file
src/index.js
to use ReactDOM.hydrate() instead of ReactDOM.render(). - Render route-based content correctly on server-side: Keep using BrowserRouter in
src/index.js
, but inserver/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. - Getting correct data on server: server-side does not execute componentDidMount, comonentDidUpdate, and useEffect hook. Only render() function will be executed. Therefore, create hooks to query your data on server-side.
Recommendations if you want to add SSR for CRA:
- Follow this guide: https://medium.com/bucharestjs/upgrading-a-create-react-app-project-to-a-ssr-code-splitting-setup-9da57df2040a
- If you don't understand anything in that guide, learn from this course: https://www.youtube.com/playlist?list=PLMhLdUN2ZKJ2f-QDFBP1iphsmPd81MQOO
© 2022 - 2024 — McMap. All rights reserved.