Have you ever wondered what <h1>{title}</h1>
really does?
At first glance, it looks like just a way to inject JavaScript variables into JSX.
But there's more to it.
It’s not just syntax.
It’s security.
JSX Escapes by Default 🛡️
React automatically escapes any content inside JSX curly braces before rendering it to the DOM.
That means special characters like <
, >
, and &
are safely converted, preventing malicious HTML or JavaScript from being interpreted.
const title = '<script>alert("XSS")</script>';
// JSX escapes it automatically
return <h1>{title}</h1>;
Output:
<h1><script>alert("XSS")</script></h1>
✅ No script executed. Just safe, visible text.
🔗 By default, React DOM escapes any values embedded in JSX before rendering them.
Why This Matters
Imagine this value came from user input (e.g., a comment form or a URL parameter).
If React didn’t escape it, this line:
<h1>{userInput}</h1>
could become an open door to XSS (Cross-site Scripting) attacks. But thanks to React's design, it's safe by default.
What About dangerouslySetInnerHTML
?
Now, this is where you need to be careful:
<div dangerouslySetInnerHTML={{ __html: userInput }} />
This bypasses React's escape mechanism.
If you use this, you’re telling React:
"I know what I'm doing. Trust me, this HTML is safe."
Which means... you need to sanitize it yourself using something like DOMPurify.
The Takeaway 🎯
{}
in JSX is more than just a way to embed variables.
It’s a safety mechanism that protects your app from script injection.
Unless you explicitly bypass it, JSX makes your rendering safe by default.
So next time you write this:
<h1>{title}</h1>
Remember — React’s got your back. 😉
Top comments (0)