Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-26 18:27:30
Original
251 people have browsed it

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>
Copy after login

2. Unicode Numbers in JSX Strings

Convert HTML entities to Unicode numbers within JSX strings:

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

3. Mixed Array of Strings and JSX Elements

Combine strings and JSX elements to render complex HTML:

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

4. DangerouslySetInnerHTML as Last Resort

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!