Render an array of items as a list, with a key for each.
What to build
A shopping list built from data.
Requirements
- Keep the
itemsarray. Render anh2with the textShopping list (N items), where N is the number of items, and aulwith oneliper item showing its name, keyed by its id.
Constraints
Use map; do not write the list items by hand.
Example
The preview shows "Shopping list (4 items)" and the four items.
Why it works
map turns each item into an li, so the list always matches the data, and the id key lets React track each item if the list changes.
Hints
Hint 1
items.map((item) => <li key={item.id}>{item.name}</li>).
Hint 2
items.length gives the number for the heading.
Solution
Show one correct solution (try it yourself first)
const items = [
{ id: "a1", name: "Rice" },
{ id: "b2", name: "Lentils" },
{ id: "c3", name: "Eggs" },
{ id: "d4", name: "Tea" },
];
export default function App() {
return (
<div>
<h2>Shopping list ({items.length} items)</h2>
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}