DEV Community

Emmanuel Gautier
Emmanuel Gautier

Posted on • Originally published at emmanuelgautier.com on

How to get a React element as an HTML string

For use cases, you may want to have the generated HTML string from your React component instead of a mounted component rendered on the page.

The simplest way is to use the renderToString function provided by the react-dom package :

import { renderToString } from 'react-dom/server'

renderToString(<YourAwesomeComponent props1="value1" props2={{ value: "2" }} />)
Enter fullscreen mode Exit fullscreen mode

The function renderToString can be used on both the server-side and client-side.

If you want to render all page server-side for SEO or UX purposes for example, you can use the function renderToNodeStream to improve your load time.

More informations on the React documentation.

Top comments (0)