If you have:
<div>
{ books.map( ( book, index ) => (
<div key={ index }>
{ book.label }
</div>
) ) }
{ movies.map( ( movie, index ) => (
<div key={ index }>
{ movie.label }
</div>
) ) }
</div>
As the index
would be 0, 1, 2, etc. That means there will be divs with the "same" key value.
Does the index being inside a .map()
make it unique or should each key be set like this to be unique in the entire app: <div key={ 'book-' index }>
and <div key={ 'movie-' index }>
?
CodePudding user response:
A key being unique to a particular returned .map
is enough. Your current code is fine - in that sense.
But it would be better not to use the index as the key, in general - if the books
or movies
arrays ever have items removed or shifted around, the index will not be reliable as a key, because the same "movie" would then have a different index. Better to pick something unique from those objects - if no two movies will have the same movie.label
, for example, that could be a good choice for a key. (or if you have anything like a unique .movieId
property, that'd work too)