Sub topic 13
Handling empty lists
This chapter assumes you know JavaScript arrays, map and filter, React function components and props, and the useState hook. It also assumes you have already rendered a list with map and given each item a key.
Why an empty list needs its own output
When an array has no items, map returns an empty array. React renders that as nothing. The user sees a blank space and can't tell whether the data is still loading, the request failed, or there is simply nothing to show.
An empty state is a short message that tells the user which case they are in. It is part of the component's output, so you write it with the same conditional tools you already know.
Early return with if
The clearest option for a whole component is to check the length first and return early.
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>
);
}The list code after the check can assume at least one item exists. Use this form when the empty case replaces everything the component would otherwise show.
Ternary inside the markup
Sometimes the component has other content that must stay visible, such as a heading or a filter control. In that case, put the choice inside the JSX with a ternary.
function Results({ results }) {
return (
<section>
<h2>Results</h2>
{results.length === 0 ? (
<p>No results found.</p>
) : (
<ul>
{results.map(result => (
<li key={result.id}>{result.title}</li>
))}
</ul>
)}
</section>
);
}The heading renders in both cases. Only the part that depends on the data changes.
Check the filtered list, not the source
An empty state must reflect what the user would actually see. If you filter the data before display, test the filtered array.
import { useState } from 'react';
function Tasks({ tasks }) {
const [hideDone, setHideDone] = useState(false);
const visible = hideDone ? tasks.filter(task => !task.done) : tasks;
return (
<>
<label>
<input
type="checkbox"
checked={hideDone}
onChange={e => setHideDone(e.target.checked)}
/>
Hide completed
</label>
{visible.length === 0 ? (
<p>Nothing to show.</p>
) : (
<ul>
{visible.map(task => (
<li key={task.id}>{task.title}</li>
))}
</ul>
)}
</>
);
}If you tested tasks.length instead, a user who has finished every task and ticked "Hide completed" would see an empty list with no message.
Common errors
- Testing the wrong array. Check the array you pass to
map, not the original data. - Using
&&with a length.{items.length && <List />}renders the number0on screen when the list is empty. Compare explicitly withitems.length > 0 &&, or use a ternary. - Reading
lengthofundefined. Data that loads later may beundefinedat first. Give the prop a default, for exampleitems = [], or handle the loading case before the length check. - Confusing empty with loading. An empty array means the data arrived and has no items. Show a loading message separately so users don't see "No results" while a request is still running.
Exercise
Exercise
A component receives notifications and renders {notifications.length && <NotificationList items={notifications} />}. What does the user see when the array is empty, and how do you fix it so the screen also shows "You're all caught up."?
Show answer
React renders the number 0, because 0 && ... evaluates to 0 and React displays numbers. Use a ternary instead: {notifications.length > 0 ? <NotificationList items={notifications} /> : <p>You're all caught up.</p>}.
Exercise
A page filters a products array by a search term into matches. Which array's length should decide whether to show "No products match your search"?
Show answer
matches. It is the array the user actually sees. Testing products.length would hide the message whenever the source has items but the filter removes them all.