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.
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
Read the <strong>docs</strong> at <a href="https://react.dev">react.dev</a>.
Raw HTML stays text: <img src=x onerror="console.log(1)">
Bad link: click