Home >Web Front-end >JS Tutorial >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' }
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;
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!