Back to results for “Security”
React › Security in React (XSS & dangerouslySetInnerHTML)

What is dangerouslySetInnerHTML and why does its name include the word dangerously?

Intermediate

Answer

dangerouslySetInnerHTML lets you insert raw HTML directly into a component, bypassing React's normal automatic protection against cross site scripting. The name is a clear warning that using it incorrectly, especially with content coming from users, can open your app up to serious security vulnerabilities.
function Article({ htmlContent }) {
  return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
}

// Only ever use this with trusted, sanitized content, never raw user input directly
Real-world example A blogging platform uses dangerouslySetInnerHTML to display rich formatted article content written by trusted staff writers, while completely avoiding this approach for anything submitted by anonymous website visitors.

Common follow-ups: How would you safely sanitize untrusted HTML before using dangerouslySetInnerHTML?;What popular libraries help clean potentially unsafe HTML before displaying it?