React Reference ยท JSX Syntax and Rules
Escaping in JSX
How React escapes values in JSX so user text cannot become markup, how HTML entities and curly braces behave, and when dangerouslySetInnerHTML is risky.
When you put a value in curly braces inside JSX, React treats it as text, not as HTML. A string such as <img src=x onerror=alert(1)> appears on the page as those literal characters; it is never parsed into elements. This is the main reason ordinary React code is resistant to cross-site scripting through rendered text.
Escaping has a second side that confuses beginners: what you type directly in JSX text, such as & or {, is handled by the JSX compiler, not by React DOM. Knowing which layer does what tells you how to write a literal ampersand, a brace or a quote, and when you are opting out of the protection.
const comment = '<b>not bold</b>'; return <p>{comment}</p>; // shows: <b>not bold</b>
Try it
Syntax
| You write | What the page shows |
|---|---|
where value is "<b>x</b>" |
The characters <b>x</b> (escaped) |
& < > " © in JSX text |
The decoded character |
"a & b" in a string attribute |
a & b (the compiler decodes it) |
{'a & b'} |
The literal text a & b (no decoding) |
{'{'} or {"}"} |
A literal brace |
dangerouslySetInnerHTML={{ __html: html }} |
html parsed as real HTML |
Edge cases: a bare { or } in JSX text is a syntax error, because braces always open or close an expression. A bare > or < in text is also reserved, so write >/< or use {'>'}. Numbers and strings render; objects do not (they throw), and booleans, null and undefined render nothing.
Usage notes
- Never build HTML strings to render. Pass the data as a value and let React escape it.
dangerouslySetInnerHTMLbypasses everything. Use it only with HTML you control or have sanitized with a vetted library; user-supplied HTML in it is a direct XSS hole.- Escaping applies to text and attribute values, not URLs.
<a href={userUrl}>can carry a dangerous scheme. Check that the protocol ishttp:,https:ormailto:before rendering. - Do not escape twice. If your data already holds
&, putting it in{...}shows&literally. Decode data once, at the boundary where it enters. - Styles and event handlers are not strings in React, so there is no injection through them; keep it that way and avoid
eval-like constructs. - Server rendering escapes the same way.
renderToStringoutputs<where the client DOM would hold<.