Home > Article > Web Front-end > How to Properly Render HTML Strings in React?
Rendering HTML Strings as Real HTML
When attempting to display HTML content as real HTML, certain scenarios may lead to unexpected results where the string is rendered as text rather than interpreted as HTML. To address this issue, it is crucial to ensure that the HTML string is enclosed in double quotes and decoded if necessary.
One approach to resolve this is to enclose the HTML string within double quotes within the dangerouslySetInnerHTML property, as demonstrated in the following example:
<div dangerouslySetInnerHTML={{ __html: '" <h1>Hi there!</h1>" ' }} />
However, if the HTML string is stored as an object, it will not be rendered as HTML. In such cases, the object must be transformed into a string before being assigned to dangerouslySetInnerHTML.
class App extends React.Component { constructor() { super(); this.state = { description: { children: "something", style: { color: "red" } } } } render() { return ( <div dangerouslySetInnerHTML={{ __html: JSON.stringify(this.state.description) }} /> ); } } ReactDOM.render(<App />, document.getElementById('root'));
Additionally, when dealing with HTML entities within the HTML string, it is essential to decode them before assigning them to dangerouslySetInnerHTML. This can be achieved using the htmlDecode function:
class App extends React.Component { constructor() { super(); this.state = { description: '<p>&lt;strong&gt;Our Opportunity:&lt;/strong&gt;</p>' } } htmlDecode(input){ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; } render() { return ( <div dangerouslySetInnerHTML={{ __html: this.htmlDecode(this.state.description) }} /> ); } } ReactDOM.render(<App />, document.getElementById('root'));
The above is the detailed content of How to Properly Render HTML Strings in React?. For more information, please follow other related articles on the PHP Chinese website!