Here is an example of how to implement server-side rendering (SSR) with React:
javascript
// server/index.js
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from '../src/App';
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
const appHtml = ReactDOMServer.renderToString(<App />);
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>My React SSR App</title>
</head>
<body>
<div id="root">${appHtml}</div>
<script src="bundle.js"></script>
</body>
</html>
`);
});
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
javascript
// src/App.js
import React from 'react';
const App = () => {
return (
<div>
<h1>Hello from React SSR!</h1>
<p>This content is rendered on the server.</p>
</div>
);
};
export default App;
In this example, we're using Express as the server and the `ReactDOMServer.renderToString()` method to render the React component on the server. The rendered HTML is then sent back to the client.
The key steps are:
1. Import the necessary modules (`express`, `react`, `react-dom/server`, and the React component to be rendered).
2. Create an Express app and set up a route to handle the initial request.
3. Use `ReactDOMServer.renderToString()` to render the React component to an HTML string.
4. Send the HTML string back to the client, along with a script tag to hydrate the client-side React application.
On the client-side, you would need to use `ReactDOM.hydrate()` instead of `ReactDOM.render()` to "hydrate" the pre-rendered content:
javascript
// client/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from '../src/App';
ReactDOM.hydrate(<App />, document.getElementById('root'));
This allows the client-side React application to pick up where the server-side rendering left off, providing a smooth transition and improved initial load time.
Citations:[1] https://github.com/sealninja/react-ssr-example
[2] https://codedamn.com/news/reactjs/server-side-rendering-reactjs
[3] https://www.youtube.com/watch?v=l5_n0Lenwy8
[4] https://www.digitalocean.com/community/tutorials/react-server-side-rendering
[5] https://www.sphinx-solution.com/blog/server-side-rendering/