Sub topic 13
Handling empty lists
This chapter assumes you can write function components, pass props, and use map, filter, and useState. It also assumes you know how keys work in a rendered list. It covers what to show when a list has no items, and how to tell the different kinds of "nothing to show" apart.
Why an empty list needs its own output
Rendering an empty array with map produces no elements, and React doesn't complain. The user sees a blank area, which could mean several things:
- The data is still loading.
- The request failed.
- The user has no items yet.
- The user has items, but a filter hides all of them.
Each case calls for different text and sometimes a different action. An empty state is the output you deliberately design for the case where the list has zero items to show.
Pattern 1: early return with if
When the whole component is a list, check for emptiness first and return a message. The list code below it then only runs when there is something to render.
function Cart({ items }) {
if (items.length === 0) {
return <p>Your cart is empty.</p>;
}
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}This is usually the clearest option. The two outputs are separate, and the main return doesn't carry a condition. Use it when the empty state replaces the entire component output.
Pattern 2: the ternary operator
If the list sits inside a larger layout, a ternary keeps the heading, toolbar, or wrapper in place and swaps only the content.
function TaskPanel({ tasks }) {
return (
<section>
<h2>Tasks</h2>
{tasks.length === 0 ? (
<p>No tasks yet.</p>
) : (
<ul>
{tasks.map(task => (
<li key={task.id}>{task.title}</li>
))}
</ul>
)}
</section>
);
}A ternary is an expression, so it fits inside JSX braces. Keep each branch short. If either branch grows past a few lines, move it into a named component or assign it to a variable above the return.
Pattern 3: && with an explicit comparison
You can also show a list only when it has items, using &&. Compare the length to a number instead of using the length itself.
function Notifications({ notifications }) {
return (
<div>
{notifications.length > 0 && (
<ul>
{notifications.map(n => (
<li key={n.id}>{n.text}</li>
))}
</ul>
)}
</div>
);
}Writing notifications.length && ... is a bug. When the array is empty, 0 && ... evaluates to 0, and React renders the number 0 on screen. A comparison such as > 0 produces false, which React renders as nothing.
The && form shows nothing in the empty case. Use it only when hiding the section is the right design. If the user needs a message, use a ternary or an early return.
Telling "no data" from "no matches"
A list that is empty because the user has nothing differs from one emptied by a filter. The first says "Add your first item". The second says "Nothing matches your search" and should offer a way to clear the filter. Treating both the same confuses people, because they think their data was lost.
Compare the source array with the filtered array to tell the cases apart.
import { useState } from 'react';
function ProductList({ products }) {
const [query, setQuery] = useState('');
const normalized = query.trim().toLowerCase();
const matches = products.filter(product =>
product.name.toLowerCase().includes(normalized)
);
let content;
if (products.length === 0) {
content = <p>No products yet. Add your first one.</p>;
} else if (matches.length === 0) {
content = (
<p>
No products match "{query}".{' '}
<button onClick={() => setQuery('')}>Clear search</button>
</p>
);
} else {
content = (
<ul>
{matches.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
return (
<div>
{products.length > 0 && (
<input
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Search products"
/>
)}
{content}
</div>
);
}Three details in this component:
- The search box only appears when there is something to search, using
products.length > 0 &&. contentis a variable assigned in anifchain. This works well when there are three or more outcomes, because nested ternaries get hard to read.trim()means a query of only spaces still matches everything, since an empty string is included in every string.
The decision order matters. Check the source data first, then the filtered result. Reversing the checks would show "No products match" to a brand-new user.
Loading, error, and empty are three states
If the list comes from a network request, an empty array is not the same as "not loaded yet". A common convention is to hold null (or undefined) before data arrives and [] once the server answers with nothing. The component then tests the cases in order.
function OrderList({ orders, error }) {
if (error) {
return <p role="alert">Could not load your orders.</p>;
}
if (orders === null) {
return <p>Loading orders...</p>;
}
if (orders.length === 0) {
return <p>You have no orders yet.</p>;
}
return (
<ul>
{orders.map(order => (
<li key={order.id}>
Order {order.id}: {order.total}
</li>
))}
</ul>
);
}If you skip the null check and initialize state to [], users see "You have no orders yet" for a moment on every page load, then the real list replaces it. That flash looks like a bug, and it can alarm someone who has orders.
Defending against missing arrays
Calling .length or .map on undefined throws and takes down the render. This happens when a prop is optional or an API field is missing. There are two ways to guard against it.
Give the prop a default value:
function TagList({ tags = [] }) {
if (tags.length === 0) {
return <p>No tags.</p>;
}
return (
<ul>
{tags.map(tag => (
<li key={tag}>{tag}</li>
))}
</ul>
);
}Defaults apply only to undefined, not to null. If your data source can send null, use const list = tags ?? []; inside the component instead. Be deliberate about which approach you pick. A default of [] turns a missing value into an empty state, which hides a loading condition. Use it only when "missing" and "empty" mean the same thing for that prop.
Making the empty state useful
A good empty state does more than say "nothing here". It tells the user why the list is empty and what to do next. Compare:
| Situation | Weak message | Better message |
|---|---|---|
| New account | "No items" | "You haven't added any items. Add your first item." |
| Search with no results | "No items" | "No items match 'lamp'. Clear search." |
| Everything completed | "No items" | "All tasks are done." |
| Permission limited | "No items" | "You don't have access to any projects. Ask an admin to invite you." |
Put the call to action in the same component as the message so it can reach the state or callback it needs. If several lists share the same layout, extract an EmptyState component that takes a message and an optional children slot.
function EmptyState({ message, children }) {
return (
<div role="status">
<p>{message}</p>
{children}
</div>
);
}
function ProjectList({ projects, onCreate }) {
if (projects.length === 0) {
return (
<EmptyState message="You have no projects yet.">
<button onClick={onCreate}>Create a project</button>
</EmptyState>
);
}
return (
<ul>
{projects.map(project => (
<li key={project.id}>{project.name}</li>
))}
</ul>
);
}The role="status" attribute makes screen readers announce the message when it appears, which matters when a filter empties the list in response to typing.
Common mistakes
- Using
length &&. It renders0. Compare with> 0. - Showing the empty state while loading. Distinguish
nullfrom[]. - One message for every empty case. Separate "no data" from "no matches".
- Rendering an empty
<ul>. It is valid HTML but gives screen reader users an empty list announcement. Skip it when there are no items. - Sorting inside the render without copying.
items.sort()mutates the prop. Use[...items].sort(...)before checking the result.
Exercise
A component receives messages as an array and renders {messages.length && <MessageList messages={messages} />}. What does the user see when messages is empty, and how do you fix it so the user sees "No messages." instead?
Show answer
The user sees the number 0, because 0 && ... evaluates to 0 and React renders numbers. Replace the expression with a ternary: {messages.length > 0 ? <MessageList messages={messages} /> : <p>No messages.</p>}. An early if (messages.length === 0) return <p>No messages.</p>; before the main return also works.
Exercise
An orders state starts as [] and is filled after a fetch completes. Users briefly see "You have no orders yet." before the list appears. What change removes the flash, and what extra check does the component need?
Show answer
Initialize the state to null to mean "not loaded yet". Add if (orders === null) return <p>Loading orders...</p>; before the orders.length === 0 check, so the empty message only appears after the server returns an empty array.