Sub topic 1
Embedding JavaScript expressions in JSX
Prerequisites
This chapter assumes you already know the following:
- Basic JavaScript: variables, arrays, objects, template literals, and arrow functions.
- Basic React: function components, props, and the general shape of JSX.
- How to run a React project, for example one created with Vite, so you can try the examples.
You do not need useState yet. It appears later in the tutorial, when lists change over time.
What this chapter covers
JSX looks like HTML, but it is JavaScript syntax. Curly braces let you step out of the markup and run JavaScript inside it. Every list and every conditional in the rest of this tutorial depends on this one mechanism. Here you will learn exactly where braces are allowed, what they can hold, and what React does with the value they produce.
Curly braces open a JavaScript expression
Inside JSX, text is just text. To use a JavaScript value, wrap it in { }.
function Greeting() {
const name = 'Ada';
const year = 2026;
return (
<p>
Hello, {name}. Next year is {year + 1}.
</p>
);
}React evaluates each pair of braces, then inserts the result into the output. The result here is Hello, Ada. Next year is 2027.
What goes between the braces must be an expression. An expression is a piece of code that produces a value. All of these are expressions:
- A variable:
name - Arithmetic:
year + 1 - A function call:
formatPrice(item.price) - A property access:
user.address.city - A ternary:
isAdmin ? 'Admin' : 'Guest' - A method call that returns an array:
people.map(...)
A statement is code that performs an action but does not produce a value. if, for, while, switch, and variable declarations are statements. They cannot go inside braces.
// Syntax error: `if` is a statement.
<p>{if (isAdmin) { 'Admin' }}</p>
// Works: a ternary is an expression.
<p>{isAdmin ? 'Admin' : 'Guest'}</p>This rule explains why the later chapters use the tools they do. map and the ternary operator work inside JSX because they are expressions. A plain if has to live outside the JSX, before the return.
Where braces can appear
Braces work in two places.
- As the content of a tag. The value becomes a child:
<h1>{title}</h1>. - As the value of an attribute. Replace the quotes with braces:
<img src={user.avatarUrl} />.
You cannot put braces around a tag name, and you cannot mix quotes and braces in one attribute value. Choose one form per attribute.
function Avatar({ user, size }) {
return (
<img
className="avatar"
src={user.avatarUrl}
alt={'Photo of ' + user.name}
width={size}
height={size}
/>
);
}Note width={size}. When size is the number 48, React receives a number. Writing width="48" would pass a string. For width the difference rarely matters, but for your own components it does. <Counter start="5" /> passes the string "5", and <Counter start={5} /> passes the number.
Double braces are an object in braces
You will often see {{ }}. This is not special syntax. The outer braces open a JavaScript expression, and the inner braces are an object literal.
function Banner() {
return (
<div style={{ backgroundColor: 'navy', color: 'white', padding: 8 }}>
Welcome back
</div>
);
}The style attribute takes an object, and the property names are camelCase (backgroundColor, not background-color).
What React does with the value
React treats each value that reaches the output according to its type. This table matters most for conditional rendering, so read it closely.
| Value | What appears on screen |
|---|---|
| String | The text |
| Number (including `0` and `NaN`) | The number as text |
| `true` or `false` | Nothing |
| `null` or `undefined` | Nothing |
| React element (JSX) | The rendered element |
| Array | Each item rendered in order, as siblings |
| Plain object | Error: objects are not valid as a React child |
Two rows deserve attention.
First, booleans, null, and undefined render nothing. That is why you can write {isLoggedIn && <Menu />}. When isLoggedIn is false, the expression evaluates to false, and React shows nothing.
Second, 0 is a number, so React prints it. This is the root of the && pitfall covered in a later chapter. Keep the table in mind until then.
Here is the object error in practice:
function Debug() {
const user = { name: 'Ada', age: 36 };
// Error: Objects are not valid as a React child.
return <p>{user}</p>;
}Render a property instead ({user.name}), or convert the object to text on purpose with {JSON.stringify(user)} while debugging.
Arrays are valid children
The last two rows of the table are the key to lists. An array of elements is a valid child, and React renders every item in sequence.
function Letters() {
const items = [<li key="a">A</li>, <li key="b">B</li>, <li key="c">C</li>];
return <ul>{items}</ul>;
}You rarely write that array by hand. You build it from data with map, which is the subject of the next chapter. The point here is that {people.map(...)} is an ordinary expression whose value happens to be an array of elements, and React already knows how to display it.
The key props in the example above are required for the same reason they will matter throughout this tutorial. Without them, React logs a warning.
Calling functions and computing values
Any function call is an expression, so you can format data right where you display it.
function formatPrice(cents) {
return '$' + (cents / 100).toFixed(2);
}
function PriceTag({ cents }) {
return <span className="price">{formatPrice(cents)}</span>;
}For anything longer than a short call, compute the value above the return and use a named variable. It keeps the JSX readable.
function OrderSummary({ order }) {
const itemCount = order.items.length;
const total = order.items.reduce((sum, item) => sum + item.cents, 0);
const label = itemCount === 1 ? '1 item' : itemCount + ' items';
return (
<p>
{label}, total {formatPrice(total)}
</p>
);
}A good rule: if the logic inside braces needs more than one line to understand, move it into a variable or a helper function.
Common errors
The following mistakes come up often when you start embedding expressions.
- Using a statement in braces.
{if (...) ...}and{for (...) ...}are syntax errors. Use a ternary,&&, ormap, or move the logic above thereturn. - Rendering an object. React throws "Objects are not valid as a React child". Render a field of the object, or an array of elements.
- Forgetting braces on an attribute.
src="user.avatarUrl"sets the literal stringuser.avatarUrl. You needsrc={user.avatarUrl}. - Returning several siblings without a wrapper. A component must return one root. Wrap siblings in a Fragment (
<>...</>) or an element. - Expecting
falseornullto print. They render nothing, so{String(flag)}is needed if you want to see the wordtrueorfalse. - Using HTML names for attributes. Use
classNameinstead ofclass, andhtmlForinstead offor.
How the pieces fit together
The flow below shows how a braced expression becomes screen output.
Putting it together
This component uses several of the ideas above: an expression in content, expressions in attributes, a computed variable, a ternary, and an array child.
const tags = ['react', 'jsx', 'lists'];
function formatPrice(cents) {
return '$' + (cents / 100).toFixed(2);
}
function ProductCard({ name, cents, imageUrl, inStock }) {
const status = inStock ? 'In stock' : 'Sold out';
return (
<article style={{ border: '1px solid #ccc', padding: 12 }}>
<img src={imageUrl} alt={name} width={96} />
<h2>{name}</h2>
<p>
{formatPrice(cents)} ({status})
</p>
<p>Topics: {tags.join(', ')}</p>
</article>
);
}Every { } here holds an expression. Nothing in it needs a statement, so the whole component is a single return. The next chapter takes the array idea further and uses map to turn data into a list of elements.
Exercise
Which of these lines is invalid inside JSX braces, and what is the fix? (a) {count + 1} (b) {items.length > 0 ? 'Some' : 'None'} (c) {if (items.length > 0) { 'Some' }}
Show answer
Line (c) is invalid, because if is a statement and braces accept only expressions. Replace it with the ternary from (b), or compute the text in a variable before the return.
Exercise
A component has const user = { name: 'Grace', role: 'admin' }; and returns <p>{user}</p>. What happens, and how do you display the name and role?
Show answer
React throws "Objects are not valid as a React child", because a plain object cannot be rendered. Render the fields instead: <p>{user.name} ({user.role})</p>.
Exercise
A component receives unread = 0 and returns <p>{unread}</p>. A second version returns <p>{unread > 0}</p>. What does each one show on screen, and why?
Show answer
The first shows 0, because numbers, including zero, render as text. The second shows nothing, because unread > 0 evaluates to the boolean false, and React renders nothing for booleans.