Sub topic 3
Using JavaScript inside JSX with curly braces
This chapter assumes you know modern JavaScript (arrow functions, destructuring, template literals) and basic HTML. You should also have read the previous chapters on function components and JSX syntax rules.
The working model
JSX is mostly static markup. Curly braces are the opening that lets JavaScript in. Anything between { and } is evaluated as a JavaScript expression, and the result is placed into the output at that spot.
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default function App() {
return <Greeting name="Ada" />;
}Here {name} reads the destructured prop. React renders Hello, Ada!. The braces work in the same way anywhere a child can appear.
What counts as an expression
An expression is code that produces a value. These all work inside braces:
- Variables and property access:
{user.name} - Function calls:
{formatDate(date)} - Arithmetic and template literals:
{price * 1.2},{${first} ${last}} - Ternaries and
&&:{isAdmin ? "Admin" : "Guest"} - Array methods such as
map
Statements do not work. You cannot put if, for, or const between braces, because they do not produce a value. Compute the value before the return, or use a ternary.
function Price({ amount, currency }) {
const formatted = amount.toFixed(2);
const label = amount === 0 ? "Free" : `${formatted} ${currency}`;
return <p>Price: {label}</p>;
}Where braces can go
Braces are allowed in two places inside a JSX element:
- As children, in the text position:
<h1>{title}</h1>. - As attribute values, in place of quotes:
<img src={user.imageUrl} />.
They are not allowed in tag names, and you cannot put them inside quotes. src="{url}" passes the literal text {url}.
What React does with the value
Strings and numbers become text. null, undefined, true, and false render nothing. Elements and arrays of elements render as UI.
A plain object is not a valid child. {user} where user is { name: "Ada" } throws an error ("Objects are not valid as a React child"). Render a field instead: {user.name}.
function Status({ count }) {
return <p>Unread: {count}</p>;
}A count of 0 renders as 0, because numbers are valid output. This matters later with &&.
The double-brace pattern
Sometimes you see {{ ... }}. This is not special syntax. The outer braces open a JavaScript expression, and the inner braces are an object literal.
function Box() {
return <div style={{ width: 64, height: 64 }}>Box</div>;
}Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `<p>{if (x) "a"}</p>` | Syntax error, `if` is a statement | Use `{x ? "a" : null}` |
| `<img src="{url}" />` | Literal text `{url}` is used | Use `src={url}` |
| `<p>{user}</p>` with an object | Runtime error | Render `{user.name}` |
| `{count && <Badge />}` with `count = 0` | Renders `0` on screen | Use `{count > 0 && <Badge />}` |
| Two root values in one pair of braces | Syntax error | Use one expression per pair |
Exercise
A component contains <p>Total: {total}</p> where total is 0, and <p>{total && <b>Paid</b>}</p>. What does each paragraph display, and how would you fix the second one so it shows nothing when total is 0?
Show answer
The first paragraph displays "Total: 0", since numbers render as text. The second displays "0", because 0 && ... evaluates to 0, which React renders. Fix it with {total > 0 && <b>Paid</b>}, or use a ternary: {total > 0 ? <b>Paid</b> : null}.
Exercise
Why does <div style={{ color: "red" }}> use two pairs of braces?
Show answer
The outer pair lets JavaScript into JSX. The inner pair is an object literal, which is the type of value style expects.