Home > Net >  JSX transform html to pure react
JSX transform html to pure react

Time:10-22

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"));

CodePudding user response:

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

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

example:

import React from 'react';
import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser';
 
class HtmlComponent extends React.Component {
  render() {
    const html = '<div>Example HTML string</div>';
    return <div>{ ReactHtmlParser(html) }</div>;
  }
}

CodePudding user response:

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);
}
  • Related