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...
JSX is a JavaScript Extension Syntax used in React to easily write HTML and JavaScript together. This is simple JSX code in React. But the browser does not understand this JSX because it's not valid JavaScript code. This is because we're assigning an HTML tag to a variable that is not a string but just HTML code.
JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.
Is JSX HTML? No, JSX is JavaScript XML, an extension of JavaScript that allows writing HTML in React. HTML is a standard markup language for documents designed for the web browser.
Use renderToStaticMarkup method - it produces HTML strings that we can transfer to the wire quickly:
const htmlString = ReactDOMServer.renderToStaticMarkup( <div ... );
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:
ReactDOMServer.renderToStaticMarkup()
to get the HTML codeParentComponent.contextTypes
to make this.context.store availableProvider
so it has access to the redux store.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With