Chapter 2 of 4
Embedding Values in JSX
Curly braces, which values render, and which quietly disappear.
Curly braces open an escape hatch back into JavaScript. Anything between them is evaluated as an expression and its result is rendered.
function Profile() {
const name = "Ada";
const year = 1843;
return (
<p>
{name} published her notes in {year}. That was {2026 - year} years ago.
</p>
);
}OutputAda published her notes in 1843. That was 183 years ago.
Expressions only, not statements
The braces hold an expression - something that produces a value. An if statement or a for loop is not an expression, so it cannot go inside braces. Use a ternary, &&, or map instead, or compute the value above the return.
function Status({ isOnline, messages }) {
// Compute anything complicated before the return
const label = isOnline ? "Online" : "Offline";
return (
<div>
<span>{label}</span>
{messages.length > 0 && <em>{messages.length} unread</em>}
{messages.map((message) => (
<p key={message.id}>{message.text}</p>
))}
</div>
);
}What React renders and what it skips
- Strings and numbers render as text.
- Arrays render each item in order.
null,undefined,trueandfalserender nothing at all.- Plain objects throw an error - React cannot guess how to display them.
{null} // renders nothing
{false} // renders nothing
{0} // renders the character 0
{["a", "b"]} // renders ab
{{ a: 1 }} // Error: Objects are not valid as a React child