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

The issue:

When we were developing the react.js based app we got in the following issue:

Warning: Each child in a list should have a unique "key" prop

The reason of the issue:

When you design component in react.js you always think about reusability of the component. But when we render same HTML block multiple times then react.js complains about not having a unique key.

As we all know that react creates a virtual DOM and it only renders the part of the DOM that has been changed. To do that react needs unique key for all possible block. So, if we can assign a unique ID to a repetitive block, then the issue will be solved.

The solution:

In our case we were looping on a repetitive block. But as soon as we added a unique ID like below the issue was resolved:

{items.map((item, i) => <Card key={item.uniqueId} item={item}/>)}

What should be the value of the key?

As this key is used by react to detect the DOM changes, it should have the following value:

  • Unique: A key cannot be identical to that of a sibling component. It should be unique to the entire DOM.
  • Static: A key should not ever change between renders. The dynamic value will degrade the performance.

Why random number as key is not good?

{items.map((item, i) => <Card key={Math.random()} item={item}/>)} // Bad approach

If we use random number as key then it will always force react to re-render each item in the list, even when this is not required. This approach is not good because it degrades the performance as Math.random() will cause many component instances and DOM nodes to be unnecessarily recreated.

Share