0

How would I add a key to a mapped variable statement like below?

  const limit = Math.max(...props.data.map(x => x.count), 0);

I'm getting an error in React stating "Each child in a list should have a unique "key" prop." I know how to add a key to an HTML object, but I'm not sure how to do it in this case.

4 Answers4

0

Basically this error means that you should add a 'key' prop for components when you do map() , to help react decide which components to re-render instead of re-rendering the whole list

you do for example :

myList.map( element  => <Component   key={element.id}     />  )

So the error is not related to the code you attached ,

0

You can try doing something like this

let mp = new Map();
for(let i=0; i<data.length;i++){
mp.set(MathmaxFunction,i)
}
console.log(mp.keys())
0

Could use mapped index:

const props = [{
  count: 8
}, {
  count: 7
}, {
  count: 3
}]
const limit = props.map((x, index) => {
  return {
    count: Math.max(x.count, 0),
    key: `elementName${index}`
  }
})

console.log(limit)

Each item would be limit.count and limit.key

Add a string 'elementName' to avoid duplicate key names

Jay
  • 87
  • 2
  • 5
0

First of all, the seems like there is no connection between the code you have mentioned in the post and the error you have mentioned. My best guess is you are getting this error because you have not used a unique key to an element somewhere you are using the map function. Find that place and add the key. Rather than generating a key in the map function use a key from the list if you already have one. As an example please refer to the id property in the following example.

enter image description here

gayanrathnayaka
  • 41
  • 1
  • 1
  • 4