Working with arrays in React may lead to React internal warning message that can be viewed in the browser console:
Warning: Each child in a list should have a unique "key" prop.
Check the render method of `Array name`.
Using a special key prop allows React internally to keep track of each element in the array of JSX, so that in case any of the elements are added, updated or deleted, React can optimize performance and keep track internally of those changes.
function Numbers(){
const numbers = [1, 2, 3, 4, 5]
const newNumbers = numbers.map(number=> {
return <li>{number}</li>
}
return (
<div>
<li>
{newNumbers}
</li>
</div
)
}
in the example above, the error message:
Warning: Each child in a list should have a unique "key" prop.
Check the render method of `newNumbers`.
will be shown on the browser console and to fix this error we must give each (li) element a special key prop, like so:
const newNumbers = numbers.map(number=> {
return (
<li> key={number}
{number}
</li>
)
}
This special key prop allows React internally to keep track of each element in the array of JSX, so that in case any of the elements are added, updated, or deleted, React can optimize performance and keep track internally of those changes.
The key should be a unique value associated with each element from the array. Since each element in the array is unique, we can just use each element for the key prop.
Any time we are creating an array of JSX elements, we must use the key prop.
Let's see a couple more examples of how this key prop can be used.
With Objects
It is often best to use the objects's id as the key:
const users = [
{ id: 1, firstName: "Duane", lastname: "Watson" },
{ id: 2, firstName: "Duane", lastname: "Johnson" },
]
const userHeadings = users.map(user => {
return <h1 key={user.id}>{user.firstaName}</h1>
})
With Non-Unique Arrays
If the array elements are not unique, and can't use the id, the element index position might be used:
const numbers = [0, 1, 2, 3, 4, 5]
const newNumbers = numbers.map((number, index)=> {
return <div key={index}</div>
});
While this will make the error message go away, it's not necessarily the best approach and React recommend only using the index as a last resort.
Top comments (1)
hey, great post!
to ensure that more people see it, make sure to add some tags to your article (i've added the react tag for you already)