简体   繁体   中英

How can I render a string in React JS which has components?

I have a String and want to render it in react JS

const htmlString = "<h1>
<Ref description=\"Magic may or may not be happening\"> hello magic</Ref></h1>"
return ( <div> <h1>
{htmlString}</h1>
 </div\>)

Can I render this htmlString in react js Please help!

You can use react-html-parser to achieve this

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

See docs here

You can use dangerouslySetInnerHTML attribute on an html element to set the string as HTML. But know that setting HTML like this in React is risky as this may expose your users to a cross-site scripting (XSS) attack. To know more on how to use it, refer here on official React docs: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

Posting an example use-case below on how to use it.

 function App() { function getMarkup() { return {__html: '<h3>My Content here..</h3>'}; // The HTML string you want to set } return ( <div className="App"> <div dangerouslySetInnerHTML={getMarkup()}></div> </div> ); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM