javascript / expert
Snippet
Sanitizing dangerouslySetInnerHTML to Prevent XSS
Using dangerouslySetInnerHTML is a security risk. To prevent Cross-Site Scripting (XSS), you must sanitize the input using a library like DOMPurify inside a useMemo hook for performance.
snippet.js
1
2
3
4
5
6
7
8
9
10
import DOMPurify from 'dompurify';const MarkdownPreview = ({ rawHtml }) => {const cleanHtml = React.useMemo(() => DOMPurify.sanitize(rawHtml),[rawHtml]);return <div dangerouslySetInnerHTML={{ __html: cleanHtml }} />;};
react
Breakdown
1
DOMPurify.sanitize(rawHtml)
Strips dangerous scripts and attributes (like 'onerror') from the HTML string.
2
dangerouslySetInnerHTML={{ __html: cleanHtml }}
React's explicit API for injecting HTML, now safe due to the previous sanitization step.