XSS in React: dangerouslySetInnerHTML and Third-Party Scripts
Understand how React's default escaping prevents XSS, when dangerouslySetInnerHTML is dangerous, and how third-party scripts introduce risk.
React's Built-In XSS Protection
React automatically escapes all values rendered via JSX before inserting them into the DOM. When you write {userInput} in JSX, React calls the equivalent of textContent assignment — the value is treated as text, never as HTML. This prevents the majority of XSS attacks in React applications by default.
What dangerouslySetInnerHTML Does
dangerouslySetInnerHTML={{ __html: htmlString }} is React's escape hatch that bypasses the automatic escaping. The name is intentionally alarming: it tells you that you are taking responsibility for the safety of the HTML string. React sets innerHTML directly, executing any HTML including scripts and event handlers.
All lessons in this course
- XSS in React: dangerouslySetInnerHTML and Third-Party Scripts
- CSRF Protection in React and API Setups
- Content Security Policy for React Apps
- Secrets Management and Environment Variables