How to Fix "Each child should have a unique key prop"
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} />)}
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()} />)}
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()} />)}
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: