Empty state
- React course
- Beginner
- Lesson 35/84
- 5 min
Add code that shows a fallback message when the list is empty.
Empty state
The last piece is EmptyState: it shows a message when the list is empty. We do conditional render with items.length === 0.
Approach: {items.length === 0 ? <EmptyState /> : <ListBody items={items} />}. This is the ternary operator; we cover it in the conditional render lesson.
The empty message guides the user: "Add an item to your list". This is basic to good UX.
Three pieces join
ShoppingApp now joins three pieces: if data exists, show ListBody; otherwise show EmptyState. This is the skeleton of a small real app.
Splitting components makes each one easy to test and reuse on its own. We flowed the data through props; state comes in later groups.
This structure is the heart of React's "divide and conquer" philosophy.
Practice EmptyState component
Complete the skeleton. Write an EmptyState component that returns <p className="empty">Your list is empty</p>. Export it.
Starter code
// Define EmptyState hereSample solution
function EmptyState() {
return <p className="empty">Your list is empty</p>;
}
export default EmptyState;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What triggers the empty state?
The length property gives the item count.- items is null
- items.length === 0 Correct answer
- never
- always
Explanation: items.length === 0 catches the empty list.
2 Empty state: fill in the missing part
{items.length === 0 ? <EmptyState /> : <ListBody items={____} />}
{items.length === 0 ? <EmptyState /> : <ListBody items={items} />}
Explanation: You passed the items array to ListBody.
3 Empty state: match the terms
| Term | Meaning |
|---|---|
EmptyState |
Empty message |
ListBody |
List body |
Item |
Single row |
ShoppingApp |
Shell |