Home > Article > Web Front-end > The title could be: Beyond dangerouslySetInnerHTML: Are there Safer Ways to Render Raw HTML in React?
Rendering Raw HTML in React with Enhanced Safety
Question:
Is using dangerouslySetInnerHTML the only method to render raw HTML in React?
Answer:
Since the initial methods described in the question, there have been advancements in React to ensure safer HTML rendering. Here are four options available today:
1. Unicode
Encode the HTML characters using Unicode. Save the file as UTF-8 and set the charset to UTF-8. Example:
<div>{'\u00b7'}</div>
2. Unicode Number
Embed the Unicode number into a JavaScript string.
<div>{String.fromCharCode(183)}</div>
3. Mixed Array
Combine strings and JSX elements into an array:
<div>{['First ', <span>&middot;</span>, ' Second']}</div>
4. DangerouslySetInnerHTML (Last Resort)
Use dangerouslySetInnerHTML as a final option:
<div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />
Recommendations:
The first three methods are preferred for safety and maintainability. Use dangerouslySetInnerHTML only when absolutely necessary.
The above is the detailed content of The title could be: Beyond dangerouslySetInnerHTML: Are there Safer Ways to Render Raw HTML in React?. For more information, please follow other related articles on the PHP Chinese website!