Home > Web Front-end > JS Tutorial > How to Properly Render HTML Strings in React?

How to Properly Render HTML Strings in React?

Patricia Arquette
Release: 2024-11-15 22:45:03
Original
335 people have browsed it

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>" ' }} />
Copy after login

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'));
Copy after login

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>&amp;lt;strong&amp;gt;Our Opportunity:&amp;lt;/strong&amp;gt;</p>'
    }
  }

    htmlDecode(input){
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes.length === 0 ? &quot;&quot; : e.childNodes[0].nodeValue;
  }

  render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: this.htmlDecode(this.state.description) }} />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template