Home > Web Front-end > JS Tutorial > How Can I Safely Render HTML Strings as JSX in React?

How Can I Safely Render HTML Strings as JSX in React?

Patricia Arquette
Release: 2024-11-26 11:39:09
Original
758 people have browsed it

How Can I Safely Render HTML Strings as JSX in React?

Converting HTML Strings to JSX in ReactJS

Problem Description:

When displaying HTML data retrieved via AJAX in ReactJS, the data often appears as plain text rather than rendered HTML elements. This is due to React's default behavior of escaping HTML to prevent cross-site scripting vulnerabilities.

Solution:

To convert HTML strings into JSX and display them as rendered HTML elements, you can use the dangerouslySetInnerHTML property. This property allows you to set the inner HTML content of an element directly.

Implementation:

To use the dangerouslySetInnerHTML property, you need to bind it to an object that contains the HTML content as a string. This object should have the following structure:

{ __html: 'Your HTML content' }
Copy after login

Here's an example of how to use the dangerouslySetInnerHTML property in ReactJS:

import React, { useState } from 'react';

const MyComponent = () => {
  const [htmlContent, setHtmlContent] = useState('');

  const handleHtml = (data) => {
    setHtmlContent(data.html);
  };

  return (
    <div>
      <button onClick={() => handleHtml({ html: '<h1>Hello, React!</h1>' })}>Load HTML</button>
      <div dangerouslySetInnerHTML={{ __html: htmlContent }} />
    </div>
  );
};

export default MyComponent;
Copy after login

In this example, the dangerouslySetInnerHTML property is used to render the HTML content retrieved from the handleHtml function as a rendered HTML element.

Caution:

Using the dangerouslySetInnerHTML property can introduce security risks if the HTML content is not properly sanitized. Always ensure that the HTML content you render is safe and trusted before using this property.

The above is the detailed content of How Can I Safely Render HTML Strings as JSX 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