Sub topic 10
Rendering conditionally
This chapter assumes you can write a function component, pass props to it, and embed expressions in JSX with curly braces. You should also be comfortable with &&, ||, the ternary operator, and destructuring in JavaScript.
A component often has to show different output depending on its props or state. React has no special template directive for this, such as v-if or *ngIf. A component is a JavaScript function, so you use ordinary JavaScript control flow: if statements, the ternary operator, and logical operators. This chapter covers each technique, when to pick it, and the mistakes that cause bugs.
What "conditional" means in React
JSX produces values. A value can be an element, a string, a number, null, or an array of these. When a component returns null, React renders nothing for it. Conditional rendering means choosing which value to return, or which value to place inside a larger piece of JSX.
Technique 1: early return with `if`
Use an if statement before the main return when a whole component changes shape. The example from this tutorial shows the pattern.
function TodoList({ todos }) {
if (todos.length === 0) {
return <p>Nothing to do.</p>;
}
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}The early return handles the special case first. The rest of the function then deals only with the normal case. This keeps the main JSX free of nested conditions. Use it for empty states, loading states, and missing data.
You can return null to render nothing at all:
function Banner({ message }) {
if (!message) {
return null;
}
return <div className="banner">{message}</div>;
}Returning null does not stop the component from being called. The function still runs. Only its output is empty.
Technique 2: the ternary operator
An if statement is a statement, not an expression, so you cannot put it inside curly braces in JSX. When the choice sits in the middle of markup, use the ternary operator condition ? a : b, which is an expression.
function LoginStatus({ isLoggedIn, name }) {
return (
<p>
{isLoggedIn ? `Signed in as ${name}` : 'Please sign in'}
</p>
);
}The ternary can also choose between elements:
function Message({ isError, text }) {
return (
<div>
{isError ? <strong className="error">{text}</strong> : <span>{text}</span>}
</div>
);
}Keep ternaries small. When one branch grows past a few lines, or you start nesting ternaries inside ternaries, move the logic into an early return, a variable, or a helper component.
Technique 3: `&&` for "show or nothing"
When one branch is "render nothing", the ternary cond ? <X /> : null can be shortened with the logical AND operator:
function Inbox({ unread }) {
return (
<section>
<h2>Inbox</h2>
{unread.length > 0 && <p>You have {unread.length} unread messages.</p>}
</section>
);
}a && b evaluates to a when a is falsy, and to b otherwise. React ignores true, false, null, and undefined when rendering, so a false result shows nothing.
The number `0` pitfall
React does render the number 0. If the left side of && is a number, a value of zero appears on screen.
function Unread({ count }) {
return (
<div>
{/* Bug: when count is 0, the page shows "0" */}
{count && <span>{count} new</span>}
</div>
);
}Fix it by making the left side a real boolean:
function Unread({ count }) {
return (
<div>
{count > 0 && <span>{count} new</span>}
</div>
);
}An empty string '' is also falsy but renders as an empty text node, which is harmless. NaN renders as the text "NaN". Compare explicitly (count > 0, Boolean(value), or !!value) when the value is not already a boolean.
Technique 4: storing JSX in a variable
When the markup is long or has several branches, assign the result to a variable with let and render it once.
function StatusBadge({ status }) {
let badge;
if (status === 'active') {
badge = <span className="badge green">Active</span>;
} else if (status === 'paused') {
badge = <span className="badge yellow">Paused</span>;
} else {
badge = <span className="badge gray">Unknown</span>;
}
return <div className="status">{badge}</div>;
}For a fixed set of values, a lookup object is often cleaner than a chain of if statements:
const LABELS = {
active: 'Active',
paused: 'Paused',
stopped: 'Stopped',
};
function StatusLabel({ status }) {
return <span className={`label label-${status}`}>{LABELS[status] ?? 'Unknown'}</span>;
}The ?? operator supplies a fallback only when the lookup gives null or undefined.
Choosing a technique
| Situation | Technique |
|---|---|
| Whole component differs, or an empty or loading state | Early return with `if` |
| Two alternatives inside markup | Ternary |
| Show something or nothing | `&&` with a boolean left side |
| Several branches or long markup | Variable with `if`/`else`, or a lookup object |
| Component should sometimes render nothing | Return `null` |
Conditional rendering and state
Conditions often depend on state. This example toggles a panel with useState:
import { useState } from 'react';
function Details({ summary, children }) {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(!open)}>
{open ? 'Hide' : 'Show'} details
</button>
{open && (
<div className="details">
<p>{summary}</p>
{children}
</div>
)}
</div>
);
}Each click flips open, React re-renders the component, and the condition is evaluated again.
What happens to state when a branch disappears
React tracks state by a component's position in the output tree. When a condition removes a component, React unmounts it and discards its state. When the condition becomes true again, the component mounts fresh, with its initial state.
import { useState } from 'react';
function Field() {
const [text, setText] = useState('');
return <input value={text} onChange={(e) => setText(e.target.value)} />;
}
function Form({ show }) {
return <div>{show && <Field />}</div>;
}When show goes from true to false and back, the input is empty again. If you want to keep the value, either keep the component mounted and hide it with CSS (for example style={{ display: show ? 'block' : 'none' }}), or move the state up to a parent that stays mounted.
A related gotcha appears when two branches render the same component type in the same position:
function Panel({ isPrimary }) {
return (
<div>
{isPrimary ? <Field /> : <Field />}
</div>
);
}React sees the same component type at the same position, so it keeps the state when isPrimary changes. To force a reset, give the two elements different key values:
{isPrimary ? <Field key="primary" /> : <Field key="secondary" />}Common errors
- Using
ifinside JSX braces.{if (x) { ... }}is a syntax error. Use a ternary,&&, or move theifabove thereturn. - Printing
0. A numeric left side of&&renders when it is zero. Compare to produce a boolean. - Returning
undefined. A component that falls off the end of a function without returning givesundefined. In current React versions this is allowed and renders nothing, but it is usually a mistake, such as a forgottenreturn. Returnnullon purpose. - Deep ternary nesting. Three nested ternaries are hard to read and review. Extract a component or use early returns.
- Calling hooks after an early return. Hooks such as
useStatemust run in the same order on every render. Put them at the top of the component, before any conditionalreturn.
The last point deserves an example:
import { useState } from 'react';
// Wrong: the hook is skipped when `user` is missing.
function Bad({ user }) {
if (!user) {
return null;
}
const [open, setOpen] = useState(false);
return <button onClick={() => setOpen(!open)}>{user.name}</button>;
}
// Right: the hook runs on every render.
function Good({ user }) {
const [open, setOpen] = useState(false);
if (!user) {
return null;
}
return <button onClick={() => setOpen(!open)}>{user.name}</button>;
}Exercises
Exercise
A component renders {messages.length && <MessageList messages={messages} />}. The page shows a stray 0 when there are no messages. Why does this happen, and how do you fix it?
Show answer
messages.length is the number 0. 0 && x evaluates to 0, and React renders the number 0 as text. Make the left side a boolean: {messages.length > 0 && <MessageList messages={messages} />}.
Exercise
A Field component holds typed text in useState. A parent renders {show && <Field />}. A user types text, hides the field, and shows it again. The text is gone. Give two ways to keep the text.
Show answer
When show is false, React unmounts Field and discards its state. First, keep Field mounted and hide it with CSS such as display: none. Second, lift the text state into a parent component that stays mounted and pass the value and a change handler to Field as props.