Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nested map function in a react component -> "unique "key" prop"

How would i get a proper Key Value in this component:

 {var.map((building, index) => {
        const handles = building.buildingVertices.map((point) => {
          return (
            <DrawingHandle
              key={`${index}_handle${point.id}`}
            />
          )
        })
        return (
          <>{handles}</> //<--- how do i get a key in here?
        )
      })}

since <>{handles}</> does not have a key value, i get the error: Warning: Each child in a list should have a unique "key" prop.

Thanks a lot!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have nested array structure, that is why react does not understand this case. You can use array.flatMap to flatten nested array and just return it:

{var.flatMap((building, index) => {
    return building.buildingVertices.map((point) => {
        return (
          <DrawingHandle
              key={`${index}_handle${point.id}`}
          />
        )
    })
})}

Or you can use full Fragment syntax and provide the key:

{var.map((building, index) => {
    const handles = building.buildingVertices.map((point) => {
      return (
        <DrawingHandle
          key={`${index}_handle${point.id}`}
        />
      )
    })
    return (
      <Fragment key={index}>{handles}</Fragment>
    )
})}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading