React - Server-rendered markup

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

server-rendered markup is one of the output format of Server-side rendering where the React components are:

  • rendered by a node server (at runtime or at build time) by generating HTML pages via a function and are added to the HTTP response to send a HTML page.
  • hydrated on the client side (ie attach event listeners to the server output)

3 - Rendering

The pages will become active, or hydrated, when the JavaScript bundle has loaded.

3.1 - Server

You need a node server.

const http = require('http')
const page = require('./.next/serverless/pages/about.js')
const server = NEW http.Server((req, res) => page.render(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))

3.2 - Static

Ie at build time

You then don't need a node server.

The website (called a progressive static site) is created at build time via a static site generator where every statically exported HTML page is an entry point to the full React application.


4 - Example

With the Welcome element.

  • The definition of Welcome tag
function Welcome(props) {
  return <h1>Hello, {}</h1>;
const myPage = <Welcome name="Nico" />;
const  toHydrateHtml = ReactDOMServer.renderToString(myPage);
  • If you would be on a server, you would use it like that. Example with a Node HTTP server
// http.createServer(function (req, res) {
//       res.writeHead(200, {'Content-Type': 'text/html');
//       res.write(toHydrateHtml);
//       res.end();
  • In our case, we just output it to the console
console.log("React SSR content to hydrate (see client side) with react attribute:");
  • Output:

5 - API

5.1 - Server Side

Server side: You can use this methods to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes:


5.2 - Client Side

On the client side (javascript serverd), you can hydrate the content with ReactDOM.hydrate() on a node that already has this server-rendered markup.

It allows to have a very performant first-load experience.

With a server rendering:

const body = renderToString(<App />);

The index.js client would looks like:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
window.onload = () => {
  ReactDOM.hydrate(<App />, document.getElementById('root'));

6 - Documentation / Reference