Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 21.1 — How React Protects You from XSS
React · Example 1 of 3

JSX shows untrusted text as text

The comment appears on screen with its angle brackets, exactly as typed. No img element was created, so its onerror could never run. The quote in the author's name stayed inside the title value instead of starting a new onmouseover attribute.

XSS happens when text from someone else is treated as code in your page. JSX escapes every string you put in text or attributes, so it always shows as text, but refs with innerHTML, dangerouslySetInnerHTML, unsafe URLs, spread props and server-rendered state can still let it in.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

A component shows a search term from the URL: div.innerHTML = 'Results for ' + q. Rewrite it safely in React.

02

Write a small helper serializeState(obj) that is safe to put inside <script type="application/json">, and show how the client reads it back.

03

Write a component that shows a user's name in bold inside a sentence ("Welcome back, Asha!") without using any HTML strings.

Explain it without notes

01

What is XSS, and what can an attacker do once their script runs in your page?

02

Exactly why is <p>{userText}</p> safe in React, both in the browser and in server rendering?

03

List the ways XSS can still get into a React app.

04

Why is putting JSON.stringify(data) inside a <script> tag dangerous, and how do you fix it?

JSX shows untrusted text as text

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

what the user sees: <img src=x onerror="console.log('this would have run')"> Nice post!
how it sits in the HTML: &lt;img src=x onerror="console.log('this would have run')"&gt; Nice post!
img elements created: 0
title attribute: Written by Ravi" onmouseover="console.log(1)
extra attributes: [ 'class', 'title' ]