List body
- React course
- Beginner
- Lesson 34/84
- 5 min
Write the ListBody component that renders items from an array.
List body
The second piece is ListBody: it draws the whole list. It takes the items prop and turns each item into an Item call with .map().
Each Item gets key={item.id} and item={item}. The key lets React track items; the item carries the data.
If the list is empty, map returns an empty array; we handle that case in the next lesson.
Calling Item
ListBody calls Item as <Item key={item.id} item={item} />. The self-closing tag ends with />; it has no children.
Here ListBody only returns the data; Item decides how it looks. This is the division of labor between components.
Later we will feed this structure with state; for now we work with fixed data.
Practice ListBody component
Complete the skeleton. Write a ListBody component; receive the items prop via destructuring. Return a <ul> with items.map(item => <Item key={item.id} item={item} />) inside. Export it.
Starter code
// Define ListBody here
// Item is already definedSample solution
function ListBody({ items }) {
return <ul>{items.map(item => <Item key={item.id} item={item} />)}</ul>;
}
export default ListBody;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 List body: fill in the missing part
{items.map(item => <Item key={____} item={item} />)}
{items.map(item => <Item key={item.id} item={item} />)}
Explanation: You gave item.id as the key.
2 What does ListBody draw for an empty array?
map returns an empty array for an empty array.- Nothing (an empty ul) Correct answer
- It shows a warning
- It throws
- It crashes
Explanation: An empty array maps to an empty list; the ul stays empty.
3 List body: match the terms
| Term | Meaning |
|---|---|
ListBody |
Draws the whole list |
Item |
Draws one row |
items prop |
Data array |
key |
Unique identity |