Sikau

React · Day 4 · about 25 min

Lists and keys

Render arrays with map().

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".

The rest of this lesson

  • What keys are really forexplain
  • Preparing data before renderingexplain
  • How many items?predict
  • Good key?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React