Rendering Lists with Keys

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

What you'll learn

ListsKeys.jsx

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>;
}

Step by step

  1. React renders <FruitList> for the first time: it calls the FruitList function.
  2. filter calls the arrow once per fruit. Apple costs 0.5, so fruit.price < 1 is true: Apple stays.
  3. Mango costs 2: false, so Mango is left out.
  4. For fruit = { id: 3, name: "Banana", price: 0.25 }, the callback returns true.
  5. filter collected the fruits that passed: cheap holds Apple and Banana.
  6. map turns each fruit into an <li>. key={fruit.id} gives each item an identity React can track.
  7. For fruit = { id: 3, name: "Banana", price: 0.25 }, the callback returns <li>Banana: $0.25</li>.
  8. items is an array of two JSX elements. React can render an array directly.
  9. {items} puts the array inside the <ul>.
  10. Two list items on the page, one per cheap fruit.

Common mistakes

Best practices

Key takeaways

Check yourself

Best key for a todo item?

Answer: todo.id. A random key changes every render.

Where does key go?

Answer: On the outer element returned by map. Each item needs its own.

·

More in Components and JSX