DEV Community

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

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

thomasxbanks profile image Thomas Banks Updated on ・1 min read

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

Discussion (3)

Collapse
captaingenesisx profile image
CaptainGenesisX

Thanks, this worked for me.

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
jmau111 profile image
Julien Maury

you'd rather use static keys

Forem Open with the Forem app