Lists

Render lists with map and key

Key points

  • Use map to show an array on screen. It applies the same JSX shape to each item in the array
  • Give the outermost element in map a key (a name tag) that's different for every item
  • For key, use a value unique to that item, like an id. Avoid the array position (index), because it shifts when you sort or delete

Try it

const fruits = [
  { id: 1, name: "Apple", price: 1.5 },
  { id: 2, name: "Banana", price: 1 },
  { id: 3, name: "Orange", price: 0.8 },
]

export default function App() {
  return (
    <ul style={{ padding: 16 }}>
      {fruits.map((fruit) => (
        <li key={fruit.id}>
          {fruit.name}: ${fruit.price.toFixed(2)}
        </li>
      ))}
    </ul>
  )
}
  1. Add "Grapes" to the array (it appears on screen automatically)
  2. Show only items priced at $1 or more (hint: filter before map)
  3. Remove key={fruit.id} and see what shows up in the Console

Common pitfalls

Put key on the "outermost" element
Put key on the outermost element that map returns. If you wrap <Card> in <Link>, put key on <Link>.
Every key must be different
If the values are the same (e.g. all "Part 1"), React can't tell which is which. Use a value unique to each item, like an id or slug.