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.
<ul>
{ items.map(x => <li key={ Math.random().toString(36).substr(2, 9) }>{x}</li>}
</ul>
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
).
Top comments (5)
This is not a good solution. Using randomly generated keys will trigger a re render every time. Src: stackoverflow.com/a/43892905
Thanks, this worked for me.
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.
How did you solved this issue? Thanks
you need to assign key={i} attribute to the each of item where ever you use array.map() javascript iterator. must be