Sub topic 1
Embedding JavaScript expressions in JSX
Prerequisites
This chapter assumes you know basic JavaScript (arrays, objects, arrow functions) and can write a React function component that takes props. It also assumes you have seen JSX syntax before. You don't need useState yet.
Curly braces open a JavaScript window
JSX looks like HTML, but it is JavaScript underneath. Curly braces {} let you step back into JavaScript inside the markup. Whatever is between the braces is evaluated, and the result becomes part of the output.
function Greeting({ name, unread }) {
const shout = name.toUpperCase();
return (
<section>
<h1>Hello, {shout}!</h1>
<p>You have {unread * 2} items, {unread > 5 ? 'many' : 'few'} unread.</p>
</section>
);
}Each pair of braces holds one expression: a variable, arithmetic, a function call, or a ternary. Every list and conditional pattern in the later chapters is built on this one rule.
Expressions, not statements
An expression produces a value. A statement performs an action and produces no value. Only expressions are allowed inside braces.
| Allowed in `{}` | Not allowed in `{}` |
|---|---|
| `user.name` | `if (...) { ... }` |
| `price * 2` | `for (...) { ... }` |
| `items.length` | `const x = 1;` |
| `ok ? 'Yes' : 'No'` | `return` |
| `items.map(fn)` | `switch (...) { ... }` |
If you need an if or a for, put it above the return and store the result in a variable. Then embed the variable. The chapter on early returns covers this pattern.
Where braces work
Braces work in two places:
- As children, between tags:
<p>{message}</p>. - As attribute values:
<img src={user.avatarUrl} alt={user.name} />.
Use quotes for fixed text (className="card") and braces for computed values (className={active ? 'card on' : 'card'}). Don't combine them, as in src="{url}". That passes the literal text {url}.
Braces don't work for tag names or attribute names. Use a capitalized variable for a dynamic component, as in <Tag />.
Double braces are an object in braces
The style attribute takes an object. That is why you see two pairs of braces. The outer pair opens the JavaScript window, and the inner pair is the object literal.
function Badge({ color }) {
return <span style={{ backgroundColor: color, padding: 4 }}>New</span>;
}What React does with the value
React turns the result of an expression into output according to its type.
| Value | Result on screen |
|---|---|
| String or number | Rendered as text. This includes `0`. |
| `null`, `undefined`, `true`, `false` | Nothing is rendered |
| Array | Each item is rendered in order |
| Plain object | Error: objects are not valid as a React child |
| React element | Rendered as that element |
The array row is what makes list rendering possible. The 0 row matters for the && pitfall later in this tutorial. Nothing renders for false or null, which is why a condition that evaluates to false can hide an element.
Common errors
- Rendering an object.
{user}whereuseris{ name: 'Ada' }throws "Objects are not valid as a React child". Render a field instead, such as{user.name}. - Using a statement.
{if (ok) { ... }}is a syntax error. Use a ternary or compute the value first. - Expecting
falseto print.{String(flag)}shows the word.{flag}shows nothing. - Quoting a computed attribute.
href="{link}"is literal text. Writehref={link}.
Exercise
Why does <p>{count}</p> show "0" when count is 0, but <p>{flag}</p> show nothing when flag is false? And what is wrong with <p>{if (ok) 'Yes'}</p>?
Show answer
React renders strings and numbers as text, and 0 is a number, so it appears. Booleans, null, and undefined render nothing, so false leaves the paragraph empty. if is a statement, and braces accept only expressions. Use {ok ? 'Yes' : null} instead.