Mike
Mike

Reputation: 778

How do you Render a React Component to a String

I am trying to figure out if I can "render" a React component to an HTML string. It is likely that the word "render" is not correct, as it implies putting it on the actual dom itself, whereas I am saying that I want to create a formatted HTML string from a react component. Example:

renderToString((
<CustomComponent>
 {children}
</CustomComponent>
))

renderToString would roughly return...

"<div><ul><li>child1</li><li>child2</li?</ul></div>"

If it is possible to "render" React down to raw html elements (that are not on the dom) that would be usable as well.

Background: In a React application that I am using, I am wrapping another non-React JavaScript library that manipulates and handles its own rendering. Currently React is being used to build controllers that manipulate the creation of objects for this library.

This library allows callback functions for creating HTML elements (as strings) that it then uses to embed onto a canvas that it manipulates.

I would like to use proper JSX to build the strings.

Any ideas?

Upvotes: 1

Views: 2161

Answers (1)

cbr
cbr

Reputation: 13652

Sounds like you're looking for ReactDOMServer.renderToStaticMarkup() or ReactDOMServer.renderToString(). Both of the functions can be used in both server and browser environments.

Upvotes: 1

Related Questions