Sub topic 10
Rendering conditionally
This chapter assumes you can write function components, embed JavaScript expressions in JSX with curly braces, and pass props. Conditional rendering means a component returns different JSX depending on its props or state. React has no special template syntax for this. You use ordinary JavaScript: if, the ternary operator, and &&.
The working model
A component is a function, so it can return different values on different calls. Whatever it returns for the current props is what React displays. The values null, undefined, true, and false render nothing. Returning null is how a component hides itself.
Early return with if
Use if when a whole case replaces the normal output. Statements such as if cannot go inside JSX curly braces, so they go before the return.
function Notice({ message }) {
if (!message) {
return null;
}
return <p className="notice">{message}</p>;
}When message is empty, Notice renders nothing. Guard clauses like this keep the main return free of nesting.
The ternary operator
Use condition ? a : b inside curly braces when you choose between two pieces of JSX in the middle of a larger tree.
function LoginStatus({ isLoggedIn, name }) {
return (
<header>
<h1>My app</h1>
{isLoggedIn ? <span>Signed in as {name}</span> : <a href="/login">Sign in</a>}
</header>
);
}You can also pick only a value, such as a class name, instead of a whole element: className={isActive ? 'tab active' : 'tab'}.
Logical AND for "show or nothing"
When there is no else branch, condition && <Element /> is shorter than a ternary with null.
function Inbox({ unreadCount }) {
return (
<div>
<h2>Inbox</h2>
{unreadCount > 0 && <p>You have {unreadCount} unread messages.</p>}
</div>
);
}If the left side is false, the expression evaluates to false, and React renders nothing.
Choosing between the forms
| Situation | Form |
|---|---|
| A whole component or branch replaces the output | `if` with early return |
| Two alternatives inside JSX | Ternary |
| Show something or nothing | `&&` with a boolean condition |
| Three or more cases | `if` / `else if` before the return, or a lookup object |
Deeply nested ternaries become hard to read. When you have more than two cases, move the logic into a variable:
function StatusBadge({ status }) {
let label;
if (status === 'loading') {
label = 'Loading...';
} else if (status === 'error') {
label = 'Something went wrong';
} else {
label = 'Ready';
}
return <span className={`badge badge-${status}`}>{label}</span>;
}Common errors
- Using
&&with a number or string on the left.0and''can leak into the output. Convert to a boolean with a comparison orBoolean(value). - Writing
ifinside JSX.{if (x) ...}is a syntax error. Use a ternary,&&, or compute the result before the return. - Forgetting to return in a branch. A branch that returns nothing gives
undefined, which React 18 and later render as nothing. The branch is silently empty rather than an error. - Assuming a hidden component keeps its state. A component that stops rendering is removed from the tree and loses its state. When it appears again, it starts fresh. This matters once you add
useState.
Exercise
A component renders {items.length && <List items={items} />}. What does the page show when items is an empty array, and how do you fix it?
Show answer
It shows the digit 0, because items.length is 0, and && returns that left value, which React renders as text. Fix it by making the condition a boolean: {items.length > 0 && <List items={items} />}.