Command Palette

Search for a command to run...

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

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.

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?

Trusted Types: HTML only from a named policy

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Trusted Types in this browser: true
policy output is TrustedHTML: true
React &lt;b&gt;<mark>hooks</mark>&lt;/b&gt; guide
<mark>Hooks</mark> &amp; "effects" explained