1

I'm having issues adding a key to my list. When I use index I get the error: "Each child in a list should have a unique "key" prop.".

const selectPfp = pfps?.map((e: string, i:number) => {
return (
  <>
    <PfpOption
    key={i}
      active={selectedPFP && selectedPFP === e}
      src={e}
      onClick={() => {
        setSelectedPFP(pfps[i]);
        console.log("clicked");
      }}
    />
  </>
);

})

1 Answers1

5

The key must be put into the outermost component's prop when returning from a .map. Here, the outermost component is the plain fragment, so do

return (
  <React.Fragment key={i}>
    <PfpOption
      active={selectedPFP && selectedPFP === e}
      ...

That said, because there's only one child of the fragment, it's completely superfluous; you may remove it entirely and do

const selectPfp = pfps?.map((e: string, i: number) => {
    return (
        <PfpOption
            key={i}
            active={selectedPFP && selectedPFP === e}
            src={e}
            onClick={() => {
                setSelectedPFP(pfps[i]);
                console.log("clicked");
            }}
        />
    );
})

Because e is the item in the array being iterated over, you can also replace pfps[i] with e. (you could also consider using a more precise variable name to make it more clear - maybe pfp?)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320