Sub topic 10
Choosing Between Two Outputs with the Ternary Operator
This chapter assumes you know JavaScript expressions, function components, props, JSX syntax, and the useState hook. You should also have read the previous chapter on if statements and early returns. Here you will learn when a ternary is the right tool, how to write one that stays readable, and which mistakes it invites.
Why a ternary exists
JSX lets you embed JavaScript expressions inside curly braces. It does not let you embed statements. An if statement is a statement, so this code is a syntax error:
function Status({ online }) {
return (
<p>
{if (online) { 'Online' } else { 'Offline' }}
</p>
);
}The ternary operator (also called the conditional operator) is an expression. It takes a condition and two alternatives, and it produces one of the two values:
condition ? valueIfTrue : valueIfFalseBecause it is an expression, you can place it anywhere JSX accepts one: in the children of an element, in an attribute value, or in a return statement.
function Status({ online }) {
return <p>{online ? 'Online' : 'Offline'}</p>;
}Only the chosen branch is evaluated. If online is true, React never computes the 'Offline' side. This matters when a branch is expensive to build or would throw an error, which we cover below.
Ternary versus if
An early return with if replaces the whole output of a component. A ternary swaps a single piece inside a larger layout. Pick based on how much of the output changes.
| Situation | Better choice |
|---|---|
| The whole component renders something different | `if` with early return |
| One part of a shared layout changes | Ternary |
| Two branches, both with content | Ternary |
| One branch with content, the other empty | `&&` (next chapter) |
| Three or more outcomes | `if` chain, a lookup object, or a helper function |
Ternaries in attributes and text
The ternary is not limited to elements. It often chooses a string for an attribute or a label for a button.
import { useState } from 'react';
function Toggle() {
const [on, setOn] = useState(false);
return (
<button
className={on ? 'btn btn-on' : 'btn btn-off'}
aria-pressed={on}
onClick={() => setOn(!on)}
>
{on ? 'Turn off' : 'Turn on'}
</button>
);
}Here one ternary picks a class name and another picks the label. When the only difference between two branches is a value, put the ternary around the value, not around the whole element. This keeps the markup in one place and avoids duplicated attributes.
Compare these two versions:
function SaveButton({ saving }) {
// Duplicated markup: easy for the two branches to drift apart.
return saving ? (
<button type="submit" className="btn" disabled>
Saving...
</button>
) : (
<button type="submit" className="btn">
Save
</button>
);
}
function SaveButtonBetter({ saving }) {
// One element, only the differing values are conditional.
return (
<button type="submit" className="btn" disabled={saving}>
{saving ? 'Saving...' : 'Save'}
</button>
);
}The second version is shorter, and a later change to className only needs to happen once.
Choosing between two elements
When the branches are genuinely different pieces of UI, wrap each branch in parentheses and format them on separate lines. This is the pattern you will see most often in real code.
function Greeting({ user }) {
return (
<header>
{user ? (
<p>Welcome back, {user.name}.</p>
) : (
<a href="/login">Log in</a>
)}
</header>
);
}The parentheses are required only when a branch spans several lines, but they make the two sides easy to scan. Many teams let Prettier do this formatting automatically.
A ternary with an empty branch
The second branch can be null, which tells React to render nothing. This works, but it is noisier than && for the one-sided case.
function Banner({ message }) {
return (
<div>
{message ? <p className="banner">{message}</p> : null}
</div>
);
}The ternary has one real advantage over && here. When the condition is not a strict boolean, message ? ... : null always yields either an element or null. The && form can leak a falsy value such as 0 into the output. The unreadCount && ... example in the next chapter shows exactly that. If you find yourself testing a number, a ternary with null is a safe default.
Ternaries and component state
Switching between two branches in the same position in the tree has a consequence for state that surprises many developers. React identifies a component by its type and its position. If both branches render the same component type at the same position, React reuses the existing instance and keeps its state.
import { useState } from 'react';
function Counter({ label }) {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
);
}
function Scoreboard() {
const [isHome, setIsHome] = useState(true);
return (
<div>
{isHome ? <Counter label="Home" /> : <Counter label="Away" />}
<label>
<input
type="checkbox"
checked={isHome}
onChange={e => setIsHome(e.target.checked)}
/>
Show home team
</label>
</div>
);
}Click the counter a few times, then toggle the checkbox. The label changes from "Home" to "Away", but the count does not reset. React saw a Counter at the same position before and after, so it kept the instance and only updated its props.
If you want each branch to have its own state, give them different keys:
{isHome ? (
<Counter key="home" label="Home" />
) : (
<Counter key="away" label="Away" />
)}Now toggling destroys one Counter and creates a fresh one. This is the same key-based reset technique covered at the end of this tutorial. If the two branches are different component types (say <Counter /> and <p>), React always discards the old one and mounts the new one, so no key is needed.
Nested ternaries and when to stop
You can chain ternaries to handle more than two outcomes:
function Badge({ status }) {
return (
<span>
{status === 'loading'
? 'Loading...'
: status === 'error'
? 'Something went wrong'
: 'Done'}
</span>
);
}This is valid, and a flat chain like this one is tolerable. Once the branches contain JSX, or the nesting goes inside a branch instead of the final else, readability drops quickly. Use one of these alternatives:
- An early-return
ifchain in the component body. - A lookup object that maps each status to its output.
- A small helper function that returns the right element.
const messages = {
loading: 'Loading...',
error: 'Something went wrong',
done: 'Done',
};
function Badge({ status }) {
return <span>{messages[status] ?? 'Unknown status'}</span>;
}The lookup version adds a fallback with ?? for unexpected values. The nested ternary has no equivalent safety net unless you add another branch.
Common errors
- Using a statement inside braces.
{if (x) ...}is a syntax error. Use a ternary, or compute the value before thereturn. - Forgetting the else side.
{ok ? <p>Fine</p>}is a syntax error. A ternary always needs both branches. Use: nullor switch to&&. - Duplicating markup. If the branches differ only in a string or boolean, move the ternary down to that value.
- Expecting state to reset. Two branches rendering the same component type in the same spot share state. Add distinct keys if you need a reset.
- Branches that throw. Because only the chosen branch runs, a ternary can guard property access:
user ? user.name : 'Guest'. For nullable chains, optional chaining is often shorter:user?.name ?? 'Guest'. - Hiding a precedence bug. The ternary has low precedence.
a + b ? x : ytests(a + b). Add parentheses when mixing it with other operators.
Putting it together
This component combines a ternary for the layout, one for an attribute, and one for a label. The data comes from props, and the toggle uses useState.
import { useState } from 'react';
function Article({ title, body }) {
const [expanded, setExpanded] = useState(false);
return (
<article>
<h2>{title}</h2>
{expanded ? (
<p>{body}</p>
) : (
<p>{body.slice(0, 80)}...</p>
)}
<button
aria-expanded={expanded}
onClick={() => setExpanded(!expanded)}
>
{expanded ? 'Show less' : 'Read more'}
</button>
</article>
);
}Both paragraphs share the same position and type, so you could simplify further with <p>{expanded ? body : body.slice(0, 80) + '...'}</p>. That moves the ternary down to the value, as recommended earlier.
Exercise
A component renders {isAdmin ? <AdminPanel /> : <UserPanel />}, and both panels keep an internal useState value. When isAdmin changes from false to true, the panel keeps the old state, even though you expected a fresh one. Both components are the same type, Panel, with a different mode prop. What is happening, and how do you fix it?
Show answer
React identifies a component by its type and its position in the tree. Both branches render a Panel at the same position, so React reuses the existing instance and only updates its props, which keeps its state. Give each branch a distinct key, for example <Panel key="admin" mode="admin" /> and <Panel key="user" mode="user" />. A changed key makes React discard the old instance and mount a new one with fresh state.
Exercise
Rewrite {count && <Badge count={count} />} as a ternary so that a count of 0 renders nothing instead of the number 0.
Show answer
{count > 0 ? <Badge count={count} /> : null}. The comparison produces a real boolean, and the null branch tells React to render nothing. The count > 0 && form also works.