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.
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);
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.