Skip to content
Tutorials Center
My learning

Topics

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 &amp; 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.

JSX
const comment = '<b>not bold</b>';
return <p>{comment}</p>;   // shows: <b>not bold</b>

Try it

User text stays text
Entities, braces and quotes

Syntax

You write What the page shows
where value is "<b>x</b>" The characters <b>x</b> (escaped)
&amp; &lt; &gt; &quot; &copy; &nbsp; in JSX text The decoded character
"a &amp; b" in a string attribute a & b (the compiler decodes it)
{'a &amp; b'} The literal text a &amp; 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 &gt;/&lt; 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.
  • dangerouslySetInnerHTML bypasses 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 is http:, https: or mailto: before rendering.
  • Do not escape twice. If your data already holds &amp;, putting it in {...} shows &amp; 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. renderToString outputs &lt; where the client DOM would hold <.