Rendering Empty States
What you'll learn: How to display a helpful fallback UI when your list data is empty instead of showing nothing at all.
When you render a list with .map(), you have to consider: what happens when the array is empty? Without handling this case, users see a blank space where content should be—no feedback, no explanation. That's confusing UX.
The solution is conditional rendering based on array length. Before mapping, check if the array is empty. If it is, render an "empty state" component or message. If not, proceed with your .map() call.
The Pattern
function TodoList({ todos }) {
return (
<div>
<h2>My Todos</h2>
{todos.length === 0 ? (
<p>No todos yet. Add one to get started!</p>
) : (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
)}
</div>
);
}
Here, todos.length === 0 checks if the array is empty. The ternary operator picks which UI to show: a friendly message or the actual list.
Why This Matters
Think of an empty state like a store with no products on the shelves. Instead of leaving customers staring at blank racks, you'd put up a sign: "New inventory arriving soon!" Same principle applies here—guide the user when there's nothing to display.
You can also use the && operator if you only want to show the list when it exists:
{todos.length > 0 && (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
)}
Key Takeaway: Always handle empty arrays gracefully—check array.length === 0 and render a helpful message or component instead of leaving users with a confusing blank screen.