How to safely use dangerouslySetInnerHTML in React

· Category: React

Short answer

dangerouslySetInnerHTML renders raw HTML inside a React element. It is the React equivalent of innerHTML and carries the same XSS risks if the content is untrusted.

Steps

  1. Avoid using it whenever possible; prefer JSX composition.
  2. If necessary, sanitize the HTML string with a library like DOMPurify.
  3. Ensure the content comes from a trusted source or has been strictly validated.

Example

import DOMPurify from 'dompurify';

function RichContent({ html }) {
  const clean = DOMPurify.sanitize(html);
  return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}

Tips

  • Never pass user input directly into dangerouslySetInnerHTML.
  • Use a Content Security Policy (CSP) as an additional defense layer.
  • Consider markdown renderers that output sanitized HTML automatically.