no-dangerously-set-innerhtml
Disallows DOM elements from using 'dangerouslySetInnerHTML'.
Full Name in eslint-plugin-react-dom
react-dom/no-dangerously-set-innerhtmlFull Name in @eslint-react/eslint-plugin
@eslint-react/dom-no-dangerously-set-innerhtmlPresets
dom
recommended
recommended-typescript
recommended-type-checked
strict
strict-typescript
strict-type-checked
Rule Details
This should be used with extreme caution! If the HTML inside isn't trusted (for example, if it's based on user data), you risk introducing an XSS vulnerability.
Read more about using dangerouslySetInnerHTML.
Examples
Using dangerouslySetInnerHTML to render raw HTML
Using dangerouslySetInnerHTML bypasses React's built-in XSS protections and should be avoided whenever possible.
// Problem: dangerouslySetInnerHTML exposes the application to XSS risks.
function MyComponent() {
return <div dangerouslySetInnerHTML={{ __html: "Hello, World!" }} />;
}Rendering Markdown with dangerouslySetInnerHTML
When converting Markdown to HTML, dangerouslySetInnerHTML can be used to display the rendered output. However, this should only be done with trusted input.
// Problem: Using dangerouslySetInnerHTML to render Markdown
import { Remarkable } from 'remarkable';
const md = new Remarkable();
function renderMarkdownToHTML(markdown) {
const renderedHTML = md.render(markdown);
return { __html: renderedHTML };
}
export default function MarkdownPreview({ markdown }) {
const markup = renderMarkdownToHTML(markdown);
return <div dangerouslySetInnerHTML={markup} />;
}Passing untrusted input to dangerouslySetInnerHTML
Passing untrusted input to dangerouslySetInnerHTML is a serious security risk that can lead to XSS attacks.
// Problem: Passing untrusted input directly to dangerouslySetInnerHTML
const post = {
content: `<img src="" onerror='alert("you were hacked")'>`,
};
export default function MarkdownPreview() {
// SECURITY HOLE: passing untrusted input to dangerouslySetInnerHTML
const markup = { __html: post.content };
return <div dangerouslySetInnerHTML={markup} />;
}Versions
Resources
Further Reading
See Also
react-dom/no-dangerously-set-innerhtml-with-children
Disallows DOM elements from usingdangerouslySetInnerHTMLandchildrenat the same time.react-dom/no-void-elements-with-children
Disallowschildrenin void DOM elements.