Sub topic 3
Using JavaScript inside JSX with curly braces
Prerequisites
This chapter assumes you know modern JavaScript: functions, arrow functions, destructuring, template literals, and array map. It also assumes you can read a basic function component that returns JSX. You should be comfortable with HTML elements and attributes, and with ES modules (import and export).
The core rule: braces open a JavaScript expression
JSX looks like HTML, but it lives inside JavaScript. Curly braces are the doorway between the two. Anything between { and } is evaluated as a JavaScript expression, and the result becomes part of the output.
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default function App() {
return <Greeting name="Ada" />;
}In Greeting, the text Hello, is plain JSX text. {name} is replaced by the value of the name variable, which is "Ada". The ! after the closing brace is plain text again.
You can use braces in two places:
- As children, between tags:
<h1>{title}</h1>. - As attribute values, in place of quotes:
<img src={user.imageUrl} />.
You cannot use braces to produce a tag name or an attribute name. <{tag}> is a syntax error. To choose a tag dynamically, store the component or tag name in a capitalized variable and use that variable as the element type.
function Heading({ level, children }) {
const Tag = `h${level}`;
return <Tag>{children}</Tag>;
}Tag must start with an uppercase letter. JSX treats lowercase names such as <tag> as built-in HTML elements, and uppercase names as variables.
Expressions, not statements
The most common error with curly braces is putting a statement where an expression is required. An expression produces a value. A statement performs an action and does not produce a value you can embed.
| Allowed inside `{}` (expressions) | Not allowed inside `{}` (statements) |
|---|---|
| Variable and property access: `{user.name}` | `if` / `else` |
| Function calls: `{formatDate(date)}` | `for` / `while` loops |
| Arithmetic: `{price * quantity}` | Variable declarations: `const x = 1` |
| Ternary: `{isAdmin ? 'Admin' : 'User'}` | `switch` |
| Logical operators: `{items.length > 0 && <List />}` | `return` |
| Template literals: `` {`Item ${id}`} `` | `try` / `catch` |
| `map`, `filter` calls: `{todos.map(...)}` |
If you need a statement, put it above the return, where ordinary JavaScript runs.
function Price({ amount, currency }) {
const formatted = new Intl.NumberFormat('en-US', {
style: 'currency',
currency,
}).format(amount);
return <p>Total: {formatted}</p>;
}The formatting work happens in normal statements. The JSX only reads the finished value. This keeps markup easy to scan.
What gets rendered for each kind of value
React decides how to display an embedded value based on its type. Knowing these rules prevents most surprises.
| Value | Result |
|---|---|
| String | Rendered as text |
| Number | Rendered as text, including `0` and `NaN` |
| `true`, `false` | Nothing is rendered |
| `null`, `undefined` | Nothing is rendered |
| Array | Each item is rendered in order |
| React element | Rendered as that element |
| Plain object | Error: objects are not valid as a React child |
Booleans and empty values render nothing
{true}, {false}, {null}, and {undefined} all produce no output. This is why {condition && <Thing />} works. When condition is false, the expression evaluates to false, and React skips it. Later chapters on conditional rendering build on this.
The same rule creates a trap with numbers.
function Inbox({ messages }) {
return (
<div>
{messages.length && <p>You have mail.</p>}
</div>
);
}When messages is empty, messages.length is 0. The && operator returns 0 because it is falsy, and React renders the number 0 on the page. Fix it by making the condition a real boolean: {messages.length > 0 && <p>You have mail.</p>}.
Objects are not valid children
This code throws an error.
function Profile() {
const user = { name: 'Ada', role: 'Engineer' };
return <p>{user}</p>;
}React reports Objects are not valid as a React child. React cannot decide how to turn an arbitrary object into text. Render the properties you want instead: {user.name} and {user.role}. If you need to inspect an object while debugging, use {JSON.stringify(user)}.
Dates are objects too. Use {date.toLocaleDateString()} and not {date}.
Functions are not rendered
If you embed a function without calling it, React warns that functions are not valid as a child and renders nothing. Write {getLabel()} and not {getLabel}. The exception is event attributes such as onClick={handleClick}, where you do want to pass the function itself. Event handling is covered in its own chapter.
Where braces go: text versus attributes
In an attribute, choose between quotes and braces by what the value is.
- Use quotes for a fixed string:
className="avatar". - Use braces for anything computed or any non-string value:
src={user.imageUrl},width={64},disabled={isLoading}.
Do not use both. src="{user.imageUrl}" passes the literal text {user.imageUrl} as the URL, which is almost never what you want.
You can mix text and expressions inside one attribute by using a template literal.
function Avatar({ user, size }) {
return (
<img
className={`avatar avatar-${size}`}
src={user.imageUrl}
alt={`Photo of ${user.name}`}
/>
);
}The "double curly braces" are not special syntax
You will often see style={{ width: 64 }}. This is not a new kind of brace. The outer pair opens a JavaScript expression. The inner pair is an object literal.
function Box() {
const boxStyle = { width: 64, height: 64, backgroundColor: 'tomato' };
return (
<>
<div style={{ width: 64, height: 64 }} />
<div style={boxStyle} />
</>
);
}Both div elements are equivalent in structure. The second form names the object first, which helps once the style grows or is reused. Attributes and style rules are covered in the next chapter.
Braces compose: nesting JSX inside expressions
An expression inside braces can itself contain JSX, and that JSX can contain more braces. This is how lists and conditionals work.
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}Read it from the outside in:
- The outer
{ ... }starts a JavaScript expression inside theul. - Inside it,
todos.map(...)runs an arrow function for each item. - That function returns JSX, wrapped in parentheses.
- Inside the
li, a new{todo.text}switches back to JavaScript.
The key attribute is needed on list items. It is explained in the chapter on lists and keys.
Gotchas
Comments inside JSX
A normal // or /* */ comment inside JSX markup is shown as text. To comment inside the markup, wrap a block comment in braces.
function Page() {
return (
<main>
{/* This comment does not appear in the output. */}
<h1>Title</h1>
</main>
);
}Inside the opening tag of an element, you can use ordinary comments between attributes, because that area is JavaScript-like syntax.
Whitespace
JSX trims whitespace at the start and end of lines and collapses line breaks between text and tags. When you need a visible space next to an expression, include it in the text on the same line.
function FullName({ first, last }) {
return <p>{first} {last}</p>;
}Here, the space between the two expressions is on one line, so it is kept. If you split {first} and {last} onto separate lines, the space disappears and the names run together.
Keep expressions short
Braces accept any expression, but long ones hurt readability. When an expression grows past one simple operation, compute it before the return and give it a name.
function Order({ items, taxRate }) {
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
const total = subtotal * (1 + taxRate);
return (
<section>
<p>Subtotal: {subtotal.toFixed(2)}</p>
<p>Total: {total.toFixed(2)}</p>
</section>
);
}Calling .toFixed(2) on a number returns a string, so the result renders as text.
Escaping
Text that you embed through braces is escaped by React before it reaches the page. If name holds <script>alert(1)</script>, React displays it as text and does not run it. This protects against a common class of injection bugs. React offers an opt-out called dangerouslySetInnerHTML, which is named as a warning. Avoid it unless you fully trust and sanitize the HTML.
Summary of the working model
{}inside JSX evaluates one JavaScript expression and inserts the result.- Only expressions are allowed. Use variables above the
returnfor anything that needs statements. - Strings and numbers render as text. Booleans,
null, andundefinedrender nothing. Arrays render each item. Plain objects throw an error. - In attributes, use quotes for fixed strings and braces for everything else.
{{ }}is a pair of braces around an object literal.- JSX nested inside an expression can contain more braces, which is how
mapand conditionals are written.
Exercise
A component receives items, an array that may be empty, and contains {items.length && <ItemList items={items} />}. What appears on the page when items is empty, and how do you fix it?
Show answer
The page shows the number 0. items.length is 0, the && operator returns that falsy value, and React renders numbers, including zero. Fix it by using a boolean condition: {items.length > 0 && <ItemList items={items} />}.
Exercise
This component fails with "Objects are not valid as a React child": function Stamp({ createdAt }) { return <p>Created {createdAt}</p>; }. createdAt is a Date. Why does it fail, and what is one correct version?
Show answer
A Date is an object, and React cannot render objects as children. Convert it to a string first, for example <p>Created {createdAt.toLocaleDateString()}</p>.
Exercise
Why does <img src="{user.imageUrl}" /> not show the user's image, and what is the correct form?
Show answer
Quotes make the attribute a plain string, so the browser receives the literal text {user.imageUrl} as the URL. Use braces instead: <img src={user.imageUrl} />.