Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 576
Philipp Avatar asked Sep 03 '16 14:09

Philipp


People also ask

Is JSX converted to 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.

Does JSX allows to write HTML in React?

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 and HTML same?

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.


2 Answers

Use renderToStaticMarkup method - it produces HTML strings that we can transfer to the wire quickly:

const htmlString = ReactDOMServer.renderToStaticMarkup(       <div ... ); 
like image 56
Igorsvee Avatar answered Sep 23 '22 00:09

Igorsvee


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.
like image 23
Philipp Avatar answered Sep 21 '22 00:09

Philipp