How to display dynamic HTML data in React?
Learn how to safely render dynamic HTML content in React using dangerouslySetInnerHTML and avoid XSS issues.
Question
How to display dynamic HTML data in React?
Answer
React escapes HTML by default to protect your app from XSS (Cross-Site Scripting) attacks.
If you try this:
<div>{htmlContent}</div>
it will literally show <p>Hello</p> instead of rendering it.
To render dynamic HTML, React gives you dangerouslySetInnerHTML — a special prop you can use when you know the source is safe.
function RenderHTML({ htmlContent }) {
return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
}
This tells React,
“Yes, I know what I’m doing — render this HTML literally.”
⚠️ But careful: if this content comes from an API or user input, always sanitize it using DOMPurify.
npm install dompurify
import DOMPurify from 'dompurify';
function SafeHTML({ htmlContent }) {
const clean = DOMPurify.sanitize(htmlContent);
return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}
Real-World Example
You’ll need this when rendering:
- Blog post content from a CMS
- Email templates
- Markdown converted to HTML
Quick Practice
Fetch an HTML string from an API (like "<h3>Hello from API</h3>")
and render it using dangerouslySetInnerHTML.
Then, add sanitization.
Summary
Use dangerouslySetInnerHTML to render HTML safely,
but always sanitize when content comes from external or user sources.
Can I use innerHTML like plain JS?
No, React escapes HTML by default. Use dangerouslySetInnerHTML instead.
Is dangerouslySetInnerHTML safe?
Only if you sanitize the HTML before rendering it. Never trust raw user input.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.