Data in, list out
Real data comes as arrays: menu items, messages, search results. In React you turn an array of data into an array of elements with map() — no loops writing HTML by hand.
map() and key
const dishes = [
{ id: 1, name: "Momo", price: 180 },
{ id: 2, name: "Sel roti", price: 60 },
{ id: 3, name: "Thukpa", price: 220 },
];
export default function Menu() {
const cheap = dishes.filter((d) => d.price < 200);
return (
<ul>
{cheap.map((d) => (
<li key={d.id}>
{d.name}: Rs {d.price}
</li>
))}
</ul>
);
}- Use ids from your data as keys. Avoid the array index if items can be reordered, added or removed.
- Keys only need to be unique among siblings, not across the whole app.
- Forget a key and React warns in the console: "Each child in a list should have a unique key prop".