How to parse html on a React component?

This is my senario:
1. Request application CMS (content management system) for the content of the page.
2. Return CMS "<div>Hi,<SpecialButton color="red">My Button</SpecialButton></div>"
3. The application consumes the content, displays the corresponding component with the data provided in the attribute.

I can't figure out how to do step 3 in React mode, any advice is welcome.

Thanks @Glenn Reyes, here is Sandbox to show the problem.

 import React from 'react'; import { render } from 'react-dom'; const SpecialButton = ({ children, color }) => ( <button style={{color}}>{children}</button> ); const htmlFromCMS = ` <div>Hi, <SpecialButton color="red">My Button</SpecialButton> </div>`; const App = () => ( <div dangerouslySetInnerHTML={{__html: htmlFromCMS}}> </div> ); // expect to be same as // const App = () => ( // <div>Hi, // <SpecialButton color="red">My Button</SpecialButton> // </div> // ); render(<App />, document.getElementById('root')); 

Here is a live demo made by Ways. The string "<div v-demo-widget></div>" can be viewed as a Vuejs directive and rendered. Source code .

+8
javascript html compilation reactjs content-management-system
source share
2 answers

You will probably want to take a deeper look at dangerouslySetInnerHTML . Here is an example of how to render HTML from a string in a React component:

 import React from 'react'; import { render } from 'react-dom'; const htmlString = '<h1>Hello World! 👋</h1>'; const App = () => ( <div dangerouslySetInnerHTML={{ __html: htmlString }} /> ); render(<App />, document.getElementById('root')); 

Full example here: https://codesandbox.io/s/xv40xXQzE

Read more about dangerouslySetInnerHTML in React docs here: https://facebook.imtqy.com/react/docs/dom-elements.html#dangerouslysetinnerhtml

+2
source share

You can use ReactDOMserver to render <MyReactComponent /> in html on your server, and then pass it to the client, where you can paste all the received html through dangerouslySetInnerHTML .

+1
source share

All Articles