React
/Advanced
dangerouslySetInnerHTML
Definition
`dangerouslySetInnerHTML` is React's replacement for using `innerHTML` in the browser DOM. It allows you to explicitly insert raw HTML strings into the DOM, bypassing React's XSS protections.
Explain Like I'm New
React puts a giant safety lock on rendering raw HTML to protect you from hackers. By forcing you to type the word `dangerously`, React is making you sign a waiver that says, 'I know what I am doing, and if I get hacked, it is my own fault.' You must provide an object `{ __html: string }` to unlock it.
Real World Example
You are fetching a blog post from a Headless CMS (like WordPress or Contentful). The CMS returns a string of pre-formatted HTML: `<h1>My Trip</h1><p>It was fun.</p>`. To render this exactly as formatted, you must use `dangerouslySetInnerHTML`.
Common Use Cases
- •Rendering Rich Text Editor output
- •Rendering data from a trusted CMS
- •Integrating with third-party libraries that return raw HTML
Interactive Example
import React from 'react'; // import DOMPurify from 'dompurify'; export default function HtmlRenderer() { const rawHtmlFromDatabase = "<h3 style='color:red;'>Hello</h3><p>This is <strong>bold</strong>.</p>"; // const cleanHtml = DOMPurify.sanitize(rawHtmlFromDatabase); const cleanHtml = rawHtmlFromDatabase; return ( <div className='p-4 border'> <h2 className='mt-4'>Dangerous Render:</h2> {/* React executes the HTML. Notice the syntax: an object with __html */} <div className='bg-gray-100 p-2' dangerouslySetInnerHTML={{ __html: cleanHtml }} /> </div> ); }
Interview Questions
basic
- Why does React force you to type 'dangerously'?
- How do you use this prop?
intermediate
- How do you sanitize HTML before setting it dangerously?
- What library is most commonly used for sanitization?
advanced
- Can you use `dangerouslySetInnerHTML` and `children` at the same time on the same element?
- How does this affect the Virtual DOM diffing algorithm?