Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: Do not use Array index in keys

Tags:

npm

reactjs

I am using index to generate key in a list. However, es-lint generates an error for the same. React doc also states that using the item index as a key should be used as last resort.

const list = children.map((child, index) =>     <li key={index}> {child} </li>); 

I considered using react-key-index. npm install react-key-index gives following error:

npm ERR! code E404

npm ERR! 404 Not Found: react-key-index@latest

Are there any suggestions on other packages that allow to generate unique key? Any suggestion on react key generator is appreciated!

like image 911
Tanvi Patel Avatar asked Oct 13 '17 17:10

Tanvi Patel


1 Answers

When you use index of an array as a key, React will optimize and not render as expected. What happens in such a scenario can be explained with an example.

Suppose the parent component gets an array of 10 items and renders 10 components based on the array. Suppose the 5th item is then removed from the array. On the next render the parent will receive an array of 9 items and so React will render 9 components. This will show up as the 10th component getting removed, instead of the 5th, because React has no way of differentiating between the items based on index.

Therefore always use a unique identifier as a key for components that are rendered from an array of items.

You can generate your own unique key by using any of the field of the child object that is unique as a key. Normal, any id field of the child object can be used if available.

Edit : You will only be able to see the behavior mentioned above happen if the components create and manage their own state, e.g. in uncontrolled textboxes, timers etc. E.g. React error when removing input component

like image 79
palsrealm Avatar answered Sep 27 '22 22:09

palsrealm