Fix React warning properly: Each child in a list should have a unique “key” prop

--

Most of us have been facing this, if you are using flow or typescript with your react project, the type checker will force you to add a key.

Many times I have seen a developer use the index as a key.

<ul>
{
employees.map((employee, index) => {
<li key={index}>{employee.name}</li>
})
}
</ul>

Bad practice!

Indexes should not be used as keys. Why?

React uses keys to identify the DOM elements, if the data changes with key remaining the same, the UI might not update.

If you still want to use indexes as keys, make sure the list is static and never changes or the items are never reordered.

Solutions

  1. I recommend either using id attribute of the object if it has one.
<li key={employee.id}>{employee.name}</li>

2. Use a randomly generated key with NanoID

const [id] = React.useState(nanoid) 
// or assign the unique id to the data object at the source
<li key={id}>{employee.name}</li>

--

--

No responses yet