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.


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!
Remove ads
Remove ads

📚 Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access Support us
Remove ads Read more on
Remove ads
Remove ads
🎉 Thank you for subscribing to our newsletter. x