Reputation: 113
I saved some editor output to the database. The output containing the html code is converted to a string like this:
"<p><span style='color: rgb(43, 51, 94); font-size: 14px; font-style: normal; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px;'>Some Content...</span> v</p>"
I got the value from the database as an object and used it in React:
<div className="content-main">
{data.content}
</div>
Result:
I did a lot of searching, but I didn't find any solution or my search was wrong. What is the correct way to convert this value to HTML in React?
Thank you for helping me.
Upvotes: 1
Views: 372
Reputation: 351
Checkout react-html-parser here: https://www.npmjs.com/package/react-html-parser.
Once installed this is all you have to do :
<div>{ ReactHtmlParser(html) }</div>
Upvotes: 2
Reputation: 1586
You can use dangerouslySetInnerHtml
method. So in your case:
const MyComponent = ({data}) => {
function createMarkup() {
return {__html: data.content};
}
return <div className="content-main" dangerouslySetInnerHTML={createMarkup()} />;
}
But, as it says here, You should be aware of the potential XSS risks:
In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:
Upvotes: 2
Reputation: 3248
By default, React escapes the HTML to prevent XSS (Cross-site scripting). If you really want to render HTML, you can use the dangerouslySetInnerHTML property:
< td dangerouslySetInnerHTML={{__html: this.state.actions}} />
React forces this intentionally-cumbersome syntax so that you don't accidentally render text as HTML and introduce XSS bugs.
Already answered Reactjs convert html string to jsx
Upvotes: 1