DEV Community

Cover image for Warning: Each child in a list should have a unique "key" prop
Thomas Rigby
Thomas Rigby

Posted on • Edited on

Warning: Each child in a list should have a unique "key" prop

To prevent ugly errors in your console when you loop through an array, React likes you to use a unique key for each child element.

We usually use the loop index. This is not advised for several reasons1, 2.

Instead try this…

Math.random().toString(36).substr(2, 9)

This will give you a (fairly) random 9-character alphanumerical string.

Alt Text

<ul>
    { items.map(x => <li key={ Math.random().toString(36).substr(2, 9) }>{x}</li>}
</ul>
Enter fullscreen mode Exit fullscreen mode

This is useful for "throwaway" keys. If you're going to be referencing the keys in any way, you need to use a unique property (like an ID or slug).


1 React Docs say so

2 Stack Overflow Bros say so

Top comments (5)

Collapse
 
kchetan92 profile image
kchetan92

This is not a good solution. Using randomly generated keys will trigger a re render every time. Src: stackoverflow.com/a/43892905

Collapse
 
captaingenesisx profile image
CaptainGenesisX

Thanks, this worked for me.

Collapse
 
amitshahc profile image
Amit Shah

Can anyone give a tip how to find that element which requires the key? i tried to add everywhere in loops, non-loops but can't find the correct one.

Collapse
 
tatianarg profile image
TatianaRG

How did you solved this issue? Thanks

Collapse
 
amitshahc profile image
Amit Shah • Edited

you need to assign key={i} attribute to the each of item where ever you use array.map() javascript iterator. must be

mostly if you use table rows or <div> or <li> whatever you are rendering with that iteration.