What is the renderToString() method in React?

Overview

In this shot, we will learn about the React renderToString() method provided by the react-dom/server module. We will also see how it is different from the normal render method provided by the react-dom module.

Normally we will render our react component from the client using ReactDom.render(). However, we can also render our react component from the server, which has its benefits. React has a react-dom/server module, which provides us the renderToString() method. The renderToString() method renders React from the server.

Benefits of server-side rendering

  1. Rendering from the client means we have more Javascript than the mark-up file. This makes our web page ranking lower in the search engine index. Server-side rendering creates HTML with loads of mark-up, which search engines can crawl.
  2. The server-side will render HTML pages faster than the client-side. The client-side renders the whole javascript app, whereas the server-side will only render HTML, which is smaller.

Code

We will write a code in the server (node). This will render our React element.

This example is to show how it works. We need to create a server and use the renderToString() in it. Then, we can access the application on localhost.

var React = require('react');
var ReactDOMServer = require('react-dom/server');
var a = ReactDOMServer.renderToString(React.createElement('h2',null,'Element rendered from Server'));
console.log(a);

Explanation

The code above explains what renderToString() is and how it can be used in the server. When we create a server and want to render HTML from the server called server-side rendering we have to use renderToString() which will render React components from the server-side.

  • Line 1: First, we need to import or require the React.

  • Line 2: Import react-dom/server module in our server file.

  • Line 4: React will provide us a method to create a HTML element, React.createElement() takes 3 parameter name/type of element, props and value the text value it will hold. ReactDomServer will provide us our renderToString() method, which takes an element as a parameter and renders it as a String on the web page from the server.

  • Line 6: We will print the value returned by the renderToString() method.