React › Security in React (XSS & dangerouslySetInnerHTML)
What is dangerouslySetInnerHTML and why does its name include the word dangerously?
IntermediateAnswer
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 directlyReal-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.