Command Palette

Search for a command to run...

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

Markdown as React elements: nothing to sanitise

This is what react-markdown does at full scale: parse the source into a tree, then create elements. The raw <img> stays text because it's a string child, and the javascript: link becomes plain text because the URL check failed. There's no dangerouslySetInnerHTML anywhere.

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?

Markdown as React elements: nothing to sanitise

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Read the <strong>docs</strong> at <a href="https://react.dev">react.dev</a>.
Raw HTML stays text: &lt;img src=x onerror="console.log(1)"&gt;
Bad link: click