Search code examples
javascriptreactjsbabeljsjsx

JSX transform html to pure react


i am new to JSX specially learning this for gutenberg blocks i am trying to somehow convert a string of html to pure react with babel i saw there is a function in babel transform to achive that but i am unable to make use of it and there are almost no information about it anywhere if there is anyway to convert things in this way please tell me what it is below is the code example

this

let str = `
<div>
    <h1>test</h1>
</div>
`

to this

/*#__PURE__*/
React.createElement("div", null, /*#__PURE__*/React.createElement("h1", null, "test"));

Solution

  • You can use react-html-parser. It does exactly that.

    https://www.npmjs.com/package/react-html-parser

    Example

    import ReactHtmlParser from 'react-html-parser';
    
    const HTMLRenderingComponent = () => {
        const htmlString = '<div>Example HTML string</div>';
        return ReactHtmlParser(htmlString);
    }