DEV Community

Koichi Kimura
Koichi Kimura

Posted on

JSX Curly Braces {} Got Your Back Behind the Scenes

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>;
Enter fullscreen mode Exit fullscreen mode

Output:

<h1>&lt;script&gt;alert("XSS")&lt;/script&gt;</h1>
Enter fullscreen mode Exit fullscreen mode

✅ 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>
Enter fullscreen mode Exit fullscreen mode

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 }} />
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Remember — React’s got your back. 😉

Top comments (0)