Each child in a list should have a unique “key” prop

It is a very common error in React. When this error occurs, your console will display the following error message 👇

Each child should have a unique key prop error in React console image

Why this error occurs ?

This error commonly happens when using the array map() method in React.
Let’s say you have an array of objects called “data” that contains information about students.

 const data = [
    { id: 1, name: "Rohit" },
    { id: 2, name: "Sumit" },
    { id: 3, name: "Navin" },
    { id: 4, name: "Sameer" },
    { id: 5, name: "Aman" },
  ];

And you want to display the name of every student in your React app. To do that you will use JavaScript’s map() method.

{data.map((student) => (
          <div>
            <p>{student.name}</p>
          </div>
        ))}

Now understand this, When React tries to display the name of the students, it needs to keep track of each name. But because they don’t have any special labels (keys), React gets confused. It’s like having two same things, and you don’t know which one is which because they don’t have any unique identifiers. React relies on those unique “keys” to properly update and manage the name.

If you forget to provide the “key” for each name, React will show an error message saying “Each child in a list should have a unique ‘key’ prop”. It means you need to assign a special identifier (a key) to each name.

How to fix this error ?

To fix the error, you need to include a “key” prop in the outermost element of the JSX you are returning inside the map callback. The key value should be a string or a number, and it should be unique for each item in the list, like an item’s ID.

{data.map((student) => (
          <div key={student.id}>
            <p>{student.name}</p>
          </div>
        ))}

In the code mentioned above, the <div> element is the outermost element in the JSX. Therefore, we provide the key prop to that element. If there were no <div> in the JSX, we would provide the key prop to the <p> element.

And if there is a parent component that encapsulates both the <div> and <p> elements, we would provide the key prop to that parent component.

Leave a Comment