Skip to content
ClapelloNotes by Barath
ReactCh 03 · 3/6
Beginner3 min readUpdated

React / 12

Curly braces: JavaScript inside JSX

TL;DR

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 it

jsx

const value = "Tasty Bites";

<p>Today: {value}</p>

on screen

Today: Tasty Bites

Strings render as text.

Pick a value. The preview really renders it with React, except the object, which would throw.
ValueOn screen
String, numberThe text. Note: 0 shows up as "0"
true, false, null, undefinedNothing
An arrayEach item, one after another
A JSX elementThat element
A plain objectError: 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.