2

I have a gallery of items. 2 items will always be the same for a memory card game (remembering 2 matching images). Now if I map through I get the error that each child should have unique key since I give id as the key. 2 of the items I render, however, are exactly the same. The only way I see is to give the index as a key, which is not good.

How can I accomplish this without passing in index.

state = {
 cards: [
   {id: 132, src="example.com/hello"},
   {id: 142, src="example.com/bye"},
   {id: 132, src="example.com/hello"},
   {id: 142, src="example.com/bye"}
 ]
}
this.state.cards.map((card)=> {
  return <div key={card.id}><img src={card.src} /> <div/>
}
javascripting
  • 1,135
  • 4
  • 25
  • 46
  • 3
    `id` in this case is not truly unique. Either you can end up using the `index` of the iterator or define a new key that is unique for a given set – Sushanth -- Feb 18 '20 at 18:46

1 Answers1

-1

@sushant has essentially answered but here's the code

this.state.cards.map((card,index)=> {
  return <div key={index}><img src={card.src} /> <div/>
}
LoXatoR
  • 529
  • 5
  • 17
  • 1
    It was trying to find a solution as using index is pretty bad and can cause bugs in animations etc – javascripting Feb 18 '20 at 21:04
  • @javascripting aah sorry my bad, I should read more carefully. How about UUIDs? I see a well detailed answer here https://stackoverflow.com/questions/39549424/how-to-create-unique-keys-for-react-elements/51428373 – LoXatoR Feb 18 '20 at 21:47