How to Fix "Each child should have a unique key prop"

How to fix common React errors
Ferenc Almasi β€’ 2022 July 22 β€’ πŸ“– 2 min read

The "Each child in a list should have a unique "key" prop." warning happens in React when you create a list of elements without the special key attribute. Keys must be assigned to each element inΒ a loop to give stable identity to elements in React.

// ❌ Invalid, will cause the above error due to missing "key" prop
{posts.map(post => <Post details={post} />)}

// βœ”οΈ Each element now has a unique key
{posts.map(post => <Post details={post} key={post.id} />)}

// βœ”οΈ You can also use the index of the array
{posts.map((post, index) => <Post details={post} key={index} />)}
Copied to clipboard!

The key is used to correctly link the component to the DOM element. Keys must also be unique across siblings. The most common way to use unique IDs is to use either an id property on the passed object or use the index of the array.

Avoid using Math.random as the key for a component, as it doesn't provide unique values, and duplicate keys can occur.

// ❌ Don't use Math.random for a key
{posts.map(post => <Post details={post} key={Math.random()} />)}
Copied to clipboard!

Keys only need to be unique among siblings. They don't need to be unique globally.

After the warning, you will also see a line mentioning to "Check the render method of `Component`.". This way, you will know exactly which component is causing the error and where to look for the bug.

Looking to improve your skills? Check out our interactive course to master React from start to finish.
Master React

When Should You Not Use Array Indexes for Keys

Using array indexes for keys is a great way to give each element in a list a unique key if you don't have an id property on your data. However, if the order of the elements can be changed, this can cause issues in React.

Think of adding, removing, reordering, or filtering elements, such as when working with filters. In order to have unique key props for reordered elements, you must use a unique ID from your data. In case you don't have IDs on your data available, you can also use the uuid NPM package to generate unique IDs for your elements.

// ❌ This will not work if the array can be sorted or filtered
{posts.map((post, index) => <Post details={post} key={index} />)}

// βœ”οΈ You must use a unqie ID in this case
{posts.map(post => <Post details={post} key={post.id} />)}

// βœ”οΈ You can also use the uuid package
import { v4 } from 'uuid'

{posts.map(post => <Post details={post} key={v4()} />)}
Copied to clipboard!
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended