Languages
[Edit]
EN

React - render component as String (HTML in String)

4 points
Created by:
Aston-Freeman
427

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'

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

Note: to see how to install react-dom/server check npm package site.

 

Practical example

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

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

console.log(reactDOMServer.renderToString(<App/>));

Result: 

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

Note:

renderToString() is the method typically used in the server-side rendering.

References

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

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