How to Use dangerouslySetInnerHTML in React Safely and Correctly
In React, use
dangerouslySetInnerHTML to insert raw HTML into a component by passing an object with a __html key. This lets you render HTML strings but should be used carefully to avoid security risks like XSS attacks.Syntax
The dangerouslySetInnerHTML attribute expects an object with a __html property containing the HTML string you want to render. It replaces the content inside the element where it is used.
Example parts:
dangerouslySetInnerHTML: React attribute to set HTML.{{ __html: htmlString }}: Object with the HTML string.
jsx
<div dangerouslySetInnerHTML={{ __html: '<p>Hello World</p>' }} />Output
<p>Hello World</p>
Example
This example shows a React functional component that uses dangerouslySetInnerHTML to render HTML content from a string variable.
jsx
import React from 'react'; export default function HtmlRenderer() { const htmlContent = '<h2>Welcome!</h2><p>This is <strong>HTML</strong> content.</p>'; return ( <div> <h1>Using dangerouslySetInnerHTML</h1> <div dangerouslySetInnerHTML={{ __html: htmlContent }} /> </div> ); }
Output
Using dangerouslySetInnerHTML
Welcome!
This is HTML content.
Common Pitfalls
Common mistakes include:
- Passing a string directly instead of an object with
__html. - Using
dangerouslySetInnerHTMLwith untrusted content, risking cross-site scripting (XSS) attacks. - Trying to use it on self-closing tags or components that don't accept children.
Always sanitize HTML content before using it.
jsx
/* Wrong way: passing string directly */ <div dangerouslySetInnerHTML='<p>Bad</p>' /> /* Right way: passing object with __html */ <div dangerouslySetInnerHTML={{ __html: '<p>Good</p>' }} />
Quick Reference
Tips for using dangerouslySetInnerHTML:
- Use only when you must insert raw HTML.
- Always sanitize input to prevent XSS.
- Remember it replaces the element's children.
- Do not use for normal React content rendering.
Key Takeaways
Use dangerouslySetInnerHTML with an object containing __html to insert raw HTML in React.
Never pass raw strings directly; always wrap them in an object with __html key.
Sanitize any HTML content before using dangerouslySetInnerHTML to avoid security risks.
It replaces the element's children, so do not use it alongside normal React children.
Use it only when necessary, as React prefers JSX for safe content rendering.