Filter an array, map it to <li> elements and give each one a key. Watch filter and map run once per item.
React · beginner · 7 min · 10 steps · free
const fruits = [
{ id: 1, name: 'Apple', price: 0.5 },
{ id: 2, name: 'Mango', price: 2 },
{ id: 3, name: 'Banana', price: 0.25 },
];
export default function FruitList() {
const cheap = fruits.filter((fruit) => fruit.price < 1);
const items = cheap.map((fruit) => (
<li key={fruit.id}>
{fruit.name}: ${fruit.price}
</li>
));
return <ul>{items}</ul>;
}<FruitList> for the first time: it calls the FruitList function.filter calls the arrow once per fruit. Apple costs 0.5, so fruit.price < 1 is true: Apple stays.fruit = { id: 3, name: "Banana", price: 0.25 }, the callback returns true.filter collected the fruits that passed: cheap holds Apple and Banana.map turns each fruit into an <li>. key={fruit.id} gives each item an identity React can track.fruit = { id: 3, name: "Banana", price: 0.25 }, the callback returns <li>Banana: $0.25</li>.items is an array of two JSX elements. React can render an array directly.{items} puts the array inside the <ul>.Answer: todo.id. A random key changes every render.
Answer: On the outer element returned by map. Each item needs its own.
← Conditional Rendering · useState: What Happens on a Click →