Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 21.2 — dangerouslySetInnerHTML and Sanitising HTML
React · Example 1 of 3

A tiny allow-list sanitiser (for learning; real apps use DOMPurify)

Only one line is logged, and it isn't this would have run: the img and the script were removed while parsing in an inert document, the bad link lost its href and onclick, and the good link kept its https: URL. This is the allow-list idea in about 30 lines. It is not complete (DOMPurify also handles SVG, MathML, namespace tricks, srcset, CSS and many browser quirks), so don't ship it.

dangerouslySetInnerHTML puts a string into the page as real HTML, so any untrusted HTML must pass through a sanitiser such as DOMPurify first; better still, render Markdown and rich content as React elements, and let Trusted Types enforce the rule.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a SafeHtml component that sanitises with DOMPurify, allows only p, b, i, a and br, and makes every link open in a new tab safely.

02

A Note component uses dangerouslySetInnerHTML only to keep line breaks (text.replace(/\n/g, "<br>")). Rewrite it without raw HTML.

03

Write a Vitest test that proves SafeHtml removes an event-handler attribute.

Explain it without notes

01

Why is the prop called dangerouslySetInnerHTML, and why does it take an object instead of a string?

02

Why must a sanitiser use an allow-list, and why should you use DOMPurify instead of writing one?

03

Compare react-markdown with marked plus DOMPurify for rendering user Markdown.

04

What are Trusted Types, and how do they work with React?

A tiny allow-list sanitiser (for learning; real apps use DOMPurify)

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

<p>Hello <b>world</b>!</p><a>bad link</a> <a href="https://react.dev">good link</a>