How do you render a fallback message when a list is empty?
Short answer
You check the array's length before mapping over it, and show a friendly message instead of an empty list when there is nothing to display. This gives users clear feedback instead of a confusing blank space on the screen.
Advertisement
AModel answer
You check the array's length before mapping over it, and show a friendly message instead of an empty list when there is nothing to display. This gives users clear feedback instead of a confusing blank space on the screen.
function TodoList({ todos }) {
if (todos.length === 0) {
return <p>You have no tasks yet, add one to get started</p>;
}
return (
<ul>
{todos.map((todo) => <li key={todo.id}>{todo.text}</li>)}
</ul>
);
}Real-world example
A task management app shows a friendly encouraging message instead of a blank white space whenever a user has completed and cleared every task from their list.
Likely follow-ups
- Should this empty check happen inside the list component itself or in its parent?
- How would you show a loading state differently from a genuinely empty list?
Related topics