Beginner LevelReact JS & React 19
What is dangerouslySetInnerHTML and how do you prevent XSS vulnerabilities?
❓ Interview Prompt: Explain `dangerouslySetInnerHTML`, innerHTML replacement, Cross-Site Scripting (XSS) attacks, and sanitizing with DOMPurify.
'dangerouslySetInnerHTML' is React's replacement for using 'innerHTML' in the browser DOM. It allows setting raw HTML strings directly inside a component:
XSS Security Risk:
Passing unsanitized user-supplied HTML opens your application to Cross-Site Scripting (XSS) attacks, allowing malicious scripts to steal session cookies or execute unauthorized actions!
•
Defense: Always sanitize raw HTML strings using a library like DOMPurify before passing them to 'dangerouslySetInnerHTML'.
Code Implementation Example
jsx
import DOMPurify from 'dompurify';
function ArticleContent({ rawHtmlFromCMS }) {
// Sanitize raw HTML string to prevent XSS script injection!
const cleanHtml = DOMPurify.sanitize(rawHtmlFromCMS);
return (
<div
dangerouslySetInnerHTML={{ __html: cleanHtml }}
/>
);
}💡Sanitizing CMS HTML with DOMPurify before setting dangerouslySetInnerHTML.
🎯 Interview Key Takeaway
Always sanitize HTML strings with DOMPurify before setting dangerouslySetInnerHTML to prevent XSS security exploits.
#dangerouslySetInnerHTML#XSS#Security#DOMPurify#Beginner
Back to all React JS & React 19 Questions→