ReactJS - renderToString() Method



Rendering React components into HTML is a common operation, particularly when working on server-side rendering (SSR). This becomes possible using the renderToString method.

What is renderToString?

React's renderToString function renders a React component into an HTML string. On the server, it is mostly used to pre-render our React app before providing it to the client as part of the initial server response. This means that our website will load faster and be more search engine friendly.

Syntax

renderToString(reactNode)

Parameters

reactNode − It is a React node to be rendered to HTML. For example <App />.

Return Value

It returns a HTML string.

Examples

Example − Greetings App

In this code we will create a React component called Greetings to show a simple greeting message. It will use server-side rendering to convert the component into an HTML string and log that string to the console. When executed, we will see the initial HTML representation of the Greetings component with a welcome heading and a message encouraging enjoyment in building with React.

// Import necessary modules
const React = require('react');
const ReactDOMServer = require('react-dom/server');

// Define a component with greetings
const Greetings = () => (
   <div>
      <h1>Welcome to React!</h1>
      <p>Hope you enjoy building with it.</p>
   </div>
);
export default Greetings;

// Render the component to a string
const htmlString2 = ReactDOMServer.renderToString(<Greetings />);

// Log the result
console.log(htmlString2);

Output

welcome to react

Example − Counter App

In this app we will create a React component (Counter) representing a simple counter with an increment button. It will use server-side rendering to convert the component into an HTML string and log that string to the console. When executed, we will see the initial HTML representation of the Counter component with a count of 0.

// Import necessary modules
const React = require('react');
const ReactDOMServer = require('react-dom/server');

// Define a component with a simple counter
class Counter extends React.Component {
   constructor() {
      super();
      this.state = { count: 0 };
   }   
   render() {
      return (
         <div>
            <h1>Counter: {this.state.count}</h1>
            <button onClick={() => this.setState({ count: this.state.count + 1 })}>
               Increment
            </button>
         </div>
      );
   }
}
export default Counter;

// Render the component to a string
const htmlString3 = ReactDOMServer.renderToString(<Counter />);

// Log the result
console.log(htmlString3);

Output

counter 3 increment

Example − Server and Client

We can use renderToString in two different ways: first is on the Server and second is on the client. So we will discuss these two one by one.

On the Server

So first we will Import the renderToString method from 'react-dom/server'. And use it to render our React app to HTML.

import { renderToString } from 'react-dom/server';
const html = renderToString(<App />);

On the client

We need a separate function, like hydrateRoot, to make the server-generated HTML interactive.

First, verify that our response includes server-rendered HTML and that we have included the scripts required to load our React components and hydrateRoot on the client side.

Server-Side Rendering (Node.js/Express)

import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import App from './App'; // Import the main React component

const app = express();
app.get('/', (req, res) => {
   
   // Server-side rendering
   const html = renderToString(<App />);
   res.send(`
      <!DOCTYPE html>
      <html>
      <head>
         <title>Server-Side Rendering</title>
      </head>
      <body>
         <div id="root">${html}</div>
         <script src="/client.js"></script>
      </body>
      </html>
   `);
});

app.listen(3000, () => {
   console.log('Server is running on http://localhost:3000');
});

Client-Side (client.js)

import React from 'react';
import { hydrateRoot } from 'react-dom'; // Import hydrateRoot
import App from './App'; // Import the main React component

// Find the root element
const rootElement = document.getElementById('root');

// Hydrate the server-rendered HTML
hydrateRoot(rootElement, <App />);

Following this method we can achieve server-side rendering while also making the content interactive on the client side, combining the benefits of both ways.

Limitations

  • React Suspense is only partially supported by renderToString. If a component waits for data, renderToString sends its fallback as HTML right away.

  • While it can be used in browsers, it is not recommended for client-side applications. There are better options available for client-side rendering.

Summary

renderToString is a useful React method for changing our components to HTML on the server side, which improves website performance and search engine optimization. Just keep in mind that it may not be the best option for client-side code.

reactjs_reference_api.htm
Advertisements