Philipp
Philipp

Reputation: 11341

Convert react JSX object to HTML

I have a react application that generates HTML output based on some configuration. Like this:

export const getHtml = (config) => {
  const {classes, children} = config
  return (<div className={classes.join(' ')}>{children}</div>);
}

Inside the react app I can easily display the resulting DOM objects, but I want to save the HTML code to DB, to display it on a different page (without loading react/parsing the config again)

I could not find a way to convert the JSX object to plain HTML...

Upvotes: 35

Views: 77530

Answers (2)

Igorsvee
Igorsvee

Reputation: 4201

Use the renderToStaticMarkup method. As per the documentation:

You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.

const htmlString = ReactDOMServer.renderToStaticMarkup(
    <div>
        ...
    </div>
);

Upvotes: 71

Philipp
Philipp

Reputation: 11341

redux code:

Here is the full code that I had to use in my react/redux application.

import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {Provider} from 'react-redux';

...

class ParentComponent extends React.Component {

    ...

    getHtml(config) {
        const {classes, children} = config
        return ReactDOMServer.renderToStaticMarkup(
            <Provider store={this.context.store}>
                <ChildComponent classes={classes}>{children}</ChildComponent>
            </Provider>
        )
    }
}

ParentComponent.contextTypes = { store: React.PropTypes.object };

Notes:

  • Use ReactDOMServer.renderToStaticMarkup() to get the HTML code
  • Specify ParentComponent.contextTypes to make this.context.store available
  • Need to wrap the ChildComponent in a Provider so it has access to the redux store.

Upvotes: 17

Related Questions