List Keys

The code in the previous lesson will output an error to the console: Warning: Each child in a list should have a unique "key" prop.

While this is just a warning and won't technically break your app now, React could confuse elements if you are updating elements of the list. React tracks changes to the DOM, and elements in a list need a unique identifier so React can properly track changes to items in the list.

That's where the key prop comes in. Add a unique key for each element in the list to fix this. Ideally, your list items will come from a database and will have a proper ID. But sometimes, all you have is the array index. This is fine, but is not recommended if the order of the items will change.

Keys only need to be unique among siblings.

Menu
Lesson 15/22
const tasks = [
  { title: "Swab the deck" },
  { title: "Drop anchor" },
  { title: "Find treasure" },
];

export default function App() {
  return (
    <div>
      <h1> Captain's Tasks </h1>
      {tasks.map((task, i) => (
        <div key={`task-${i}`}> {task.title} </div>
      ))}
    </div>
  );
}