Trusted Types: HTML only from a named policy
The preview doesn't send the Trusted Types CSP header, so plain strings would also work here; on a site that sends it, only TrustedHTML values are accepted. React hands the TrustedHTML object straight to innerHTML. Notice the policy itself does nothing ((s) => s): it's only safe because highlight escapes every piece of user text. A policy is a promise that you checked; keep the code that feeds it small and reviewed.
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.
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.
A Note component uses dangerouslySetInnerHTML only to keep line breaks (text.replace(/\n/g, "<br>")). Rewrite it without raw HTML.
Write a Vitest test that proves SafeHtml removes an event-handler attribute.
Explain it without notes
Why is the prop called dangerouslySetInnerHTML, and why does it take an object instead of a string?
Why must a sanitiser use an allow-list, and why should you use DOMPurify instead of writing one?
Compare react-markdown with marked plus DOMPurify for rendering user Markdown.
What are Trusted Types, and how do they work with React?
Preview
Console
Nothing logged yet.Expected console output
Trusted Types in this browser: true
policy output is TrustedHTML: true
React <b><mark>hooks</mark></b> guide
<mark>Hooks</mark> & "effects" explained