How to Use innerHTML Safely in React
In React, directly manipulating the DOM is discouraged because React manages the DOM for you. However, there are rare cases — like embedding third-party HTML snippets — where you might need to set HTML manually.
For these cases, React provides a special prop called dangerouslySetInnerHTML
.
Example Usage
function HtmlContent({ html }) { return ( <div dangerouslySetInnerHTML={{ __html: html }} /> ); }
Here, html
is a string containing your HTML markup.
Why "Dangerous"?
React names it dangerouslySetInnerHTML
on purpose — setting raw HTML can expose your app to Cross-Site Scripting (XSS) attacks if you're inserting unsanitized content. An attacker could inject malicious scripts into your page if you are not careful.
How to Use it Safely
-
Always Sanitize the HTML:
If the HTML comes from an untrusted source (like user input or external APIs), sanitize it first. Use libraries like:- DOMPurify
- sanitize-html
Example with DOMPurify:
import DOMPurify from 'dompurify'; function SafeHtmlContent({ html }) { const cleanHtml = DOMPurify.sanitize(html); return ( <div dangerouslySetInnerHTML={{ __html: cleanHtml }} /> ); }
-
Prefer Alternative Approaches:
Whenever possible, avoid raw HTML injection. Render data using JSX instead.
For example, instead of inserting<b>
tags via HTML, use:<strong>Your Text</strong>
-
Limit Use to Trusted Sources:
Only usedangerouslySetInnerHTML
if you completely trust the content or have fully sanitized it.
Quick Summary
- Use
dangerouslySetInnerHTML={{ __html: html }}
for inserting HTML. - Always sanitize untrusted HTML before rendering.
- Use libraries like DOMPurify for safety.
- Avoid using
innerHTML
unless absolutely necessary.