React / 12
Curly braces: JavaScript inside JSX
Braces open a window from markup back into JavaScript. Any expression fits; statements don't. Here's exactly what each kind of value renders.
Two places braces go
const dish = { name: "Masala Dosa", price: 80, photo: "/dosa.png" };
const card = (
<article className="card">
<img src={dish.photo} alt={dish.name} />
<h3>{dish.name}</h3>
<p>₹{dish.price} · {dish.price > 100 ? "Premium" : "Value pick"}</p>
</article>
);- As content, between tags:
<h3>{dish.name}</h3>. - As an attribute value, instead of quotes:
src={dish.photo}.
Quotes give you a string, always. Braces give you whatever the expression evaluates to: a number, a function, an object, another element.
Expressions yes, statements no
An expression produces a value. A statement does something but produces nothing you could print. Braces only accept expressions, because the compiler drops them straight into a function call, like jsx("h3", { children: dish.name }).
Works in {} (expressions) | Doesn't (statements) |
|---|---|
{dish.name} | {if (open) { … }} |
{price * qty} | {for (const d of dishes) { … }} |
{formatPrice(80)} | {const total = 5} |
{open ? "Open" : "Closed"} | {switch (day) { … }} |
{open && <Badge />} | |
{`Table ${table}`} | |
{dishes.map((d) => <li key={d.id}>{d.name}</li>)} |
Need an if? Do it before the return, store the result in a variable, then put the variable in braces.
What each value renders
What does {value} show?
Try itjsx
const value = "Tasty Bites";
<p>Today: {value}</p>on screen
Today: Tasty Bites
Strings render as text.
| Value | On screen |
|---|---|
| String, number | The text. Note: 0 shows up as "0" |
true, false, null, undefined | Nothing |
| An array | Each item, one after another |
| A JSX element | That element |
| A plain object | Error: objects are not valid as a React child |
Because booleans and null render nothing, they're perfect for showing things conditionally:
{isOpen ? <span>Open now</span> : <span>Closed</span>}
{isVeg && <span className="veg-badge">Veg</span>}Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
