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

Time:08-04

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!

CodePudding user response:

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>
    )
})}

CodePudding user response:

Why not assign a key to a return div?

{var.map((building, index) => {
        const handles = building.buildingVertices.map((point) => {
          return (
            <DrawingHandle
              key={`${index}_handle${point.id}`}
            />
          )
        })
        return (
          <div key={index}>{handles}</div>
        )
      })}
  • Related