Home  >  Article  >  Web Front-end  >  How to Render Raw HTML in React Safely Without `dangerouslySetInnerHTML`?

How to Render Raw HTML in React Safely Without `dangerouslySetInnerHTML`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 18:27:30252browse

How to Render Raw HTML in React Safely Without `dangerouslySetInnerHTML`?

Render Raw HTML in React using Safer Methods

In React, you can now render raw HTML using safer methods, avoiding the use of dangerouslySetInnerHTML. Here are four options:

1. Unicode Encoding

Use Unicode characters to represent HTML entities in a UTF-8 encoded file:

<div>{`First \u00b7 Second`}</div>

2. Unicode Numbers in JSX Strings

Convert HTML entities to Unicode numbers within JSX strings:

<div>{`First ` + String.fromCharCode(183) + ` Second`}</div>

3. Mixed Array of Strings and JSX Elements

Combine strings and JSX elements to render complex HTML:

<div>{[`First `, <span>&middot;</span>, ` Second`]}</div>

4. DangerouslySetInnerHTML as Last Resort

Only use dangerouslySetInnerHTML as a last resort, as it introduces potential security vulnerabilities:

<div dangerouslySetInnerHTML={{__html: `First &middot; Second`}} />

The above is the detailed content of How to Render Raw HTML in React Safely Without `dangerouslySetInnerHTML`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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