Languages
[Edit]
EN

React - render component as String (HTML in String)

4 points
Created by:
Aston-Freeman
787

In this article, we would like to show how to render component as HTML string in React.

Quick solution: 

import React from 'react';
import ReactDOMServer from 'react-dom/server'

import App from './App';

const html = ReactDOMServer.renderToString(<App />);

// Where: html variable contains application rendered as HTML string.

Note: to know how to install react-dom/server check the below section.

 

Practical example

In this section you can see how using renderToString() method, render application as HTML string, what is typically used in the server-side rendering (SSR).

Simple steps:

1. install react-dom/server package using:

npm install react-dom

2. create index.jsx file:

import React from 'react';
import ReactDOMServer from 'react-dom/server';

const App = () => {
    return (
        <div className="App">
          Some text inside...
        </div>
    );
};

const html = ReactDOMServer.renderToString(<App/>);

console.log(html);

3. run *.js file using:

node build/static/js/main.*.js

Result: 

<div class="App" data-reactroot="">Some text inside...</div>

Screenshot:

React component rendering as HTML String under VS Code.
React component rendering as HTML String under VS Code.

References

  1. ReactDOMServer.renderToString() - React docs
  2. https://www.npmjs.com/package/react
  3. https://www.npmjs.com/package/react-dom

Alternative titles

  1. React - render component as HTML String
  2. React - get component as HTML String
  3. React - get component as String (HTML in String)
  4. React - render component to HTML String
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - render component as String (HTML in String)
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join