Sub topic 10
Choosing between two outputs with the ternary operator
This chapter assumes you know JavaScript arrays and arrow functions, React function components, props, and JSX, and the useState hook. You should also have read the previous chapter on if and early return.
Why a ternary
An if statement cannot go inside JSX, because JSX braces accept only expressions, which are pieces of code that produce a value. When the choice is between two outputs and you want to keep the surrounding markup in place, use the ternary operator. Its form is condition ? valueIfTrue : valueIfFalse, and it is an expression.
An early return is better when the whole component should change. A ternary is better when only one part of the markup changes.
A basic example
This component switches one part of its output and keeps the rest the same:
function Greeting({ user }) {
return (
<header>
<h1>Welcome</h1>
{user ? <p>Signed in as {user.name}</p> : <a href="/login">Sign in</a>}
</header>
);
}The <h1> always renders. The paragraph or the link renders depending on user. An early return would have forced you to repeat the header in both branches.
Ternaries in lists
A ternary is a natural way to show an empty state, which is a message shown in place of an empty list. The Todos component from this tutorial uses one:
{visible.length === 0 ? (
<p>Nothing to show.</p>
) : (
<ul>
{visible.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)}Wrapping each branch in parentheses lets you split multi-line JSX cleanly. Notice that the map call sits inside the second branch. It is just another expression.
Choosing a value, not a whole element
A ternary can also pick just a small piece, such as a prop or a string. This avoids duplicating an element:
function SaveButton({ saving }) {
return (
<button disabled={saving}>
{saving ? 'Saving...' : 'Save'}
</button>
);
}Here the button exists in both states. Only its label changes. Writing two separate <button> elements would be longer and easier to get out of sync.
Common errors
- Nesting ternaries.
a ? x : b ? y : zworks, but it is hard to read. Move the logic into a variable before thereturn, or into anifwith an early return. - Using a ternary when one branch is empty.
cond ? <Badge /> : nullis valid, butcond && <Badge />is shorter. Be careful with numbers, which the next chapter covers. - Forgetting that state can persist. If both branches render the same component type in the same position, React reuses the instance and keeps its state. Giving each branch a different
keymakes React treat them as separate components. - Placing statements in braces.
{if (x) ...}is a syntax error. Only expressions are allowed there.
Practice
Exercise
A Badge component receives count. Using a ternary, render <span>{count} new</span> when count is greater than 0, and <span>No new items</span> otherwise. Write the JSX expression.
Show answer
{count > 0 ? <span>{count} new</span> : <span>No new items</span>}
Exercise
Why does {if (isAdmin) <AdminPanel />} fail inside JSX, and what is a fix?
Show answer
JSX braces accept only expressions, and if is a statement. Use a ternary such as {isAdmin ? <AdminPanel /> : null}, or compute the value before the return.