dangerouslySetInnerHTML: XSS Protection by Design
What you'll learn: Why React makes inserting raw HTML deliberately difficult to protect you from security vulnerabilities.
The Security Problem
When you interpolate strings in JSX, React automatically escapes HTML characters. This is a safety feature. If a user enters <script>alert('hacked')</script> into a text field, React renders it as harmless text, not executable code. This prevents Cross-Site Scripting (XSS) attacks, where malicious scripts steal data or hijack user sessions.
The Deliberate Friction
Sometimes you legitimately need to insert raw HTML (like from a sanitized CMS or markdown parser). React doesn't make this impossible—it makes it intentionally awkward:
function UnsafeComponent() {
const htmlString = "<strong>Bold text</strong>";
// This renders the literal string:
return <div>{htmlString}</div>;
// To actually render HTML, you must:
return <div dangerouslySetInnerHTML={{__html: htmlString}} />;
}
The property name dangerouslySetInnerHTML screams that you're doing something risky. The double-underscore syntax {{__html: ...}} adds extra friction—you can't accidentally type this.
Why This Design Matters
Think of it like a medicine bottle with a child-proof cap. The cap doesn't prevent adults from opening it; it just ensures you can't do it thoughtlessly. Every time you use dangerouslySetInnerHTML, you're forced to ask: "Is this HTML actually safe? Did I sanitize user input first?"
Never pass unsanitized user input to dangerouslySetInnerHTML. If you do, attackers can inject malicious scripts into your app.
Key Takeaway: React's dangerouslySetInnerHTML prop forces you to explicitly opt into raw HTML rendering, making XSS vulnerabilities harder to introduce accidentally through its deliberately verbose and warning-laden API.