javascript / intermediate
Snippet
Sanitizing Rich HTML Content Before Injecting with dangerouslySetInnerHTML
Passing unsanitized user-generated markup into `dangerouslySetInnerHTML` exposes React applications to Cross-Site Scripting (XSS) attacks. By sanitizing the string using a library like DOMPurify inside a `useMemo` hook, you strip out malicious executable tags (`<script>`, `<iframe>`) and dangerous attribute-based event handlers (`onload`, `onerror`) before injecting the trusted markup into the DOM tree.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import DOMPurify from 'dompurify';function ArticleViewer({ rawHtmlContent }) {const cleanHtml = React.useMemo(() => {if (typeof rawHtmlContent !== 'string') return '';return DOMPurify.sanitize(rawHtmlContent, {USE_PROFILES: { html: true },FORBID_TAGS: ['script', 'iframe', 'object'],});}, [rawHtmlContent]);return (<articleclassName="article-body"dangerouslySetInnerHTML={{ __html: cleanHtml }}/>);}
react
Breakdown
1
return DOMPurify.sanitize(rawHtmlContent, {
Parses and purifies the raw HTML string against strict security rules to strip malicious elements.
2
FORBID_TAGS: ['script', 'iframe', 'object'],
Explicitly restricts dangerous tags that could execute unauthorized scripts or embed external contexts.
3
dangerouslySetInnerHTML={{ __html: cleanHtml }}
Injects the validated, purified HTML markup directly as children of the article element.