-1

I am getting this Warning: Each child in a list should have a unique "key" prop.' in my react aplication. I read this doc https://reactjs.org/docs/lists-and-keys.html#keys

And I am ready doing this in my code.

<div className="App">
    {data.map((category) => {
        return (
            <>
                <Label key={category.key}>{category.key}</Label>
            </>
        );
    }
    )}
</div>

And my data is

 const data: any[] = [
    {
        key: "Main 1",
        items: [
            { key: "subitem1", checked: true },
        ]
    },
    {
        key: "Main 2",
        items: [
            { key: "subitem2, checked: true },
        ]
    }
]

I have installed the React plugin in my browser. But I don't see how can I find out which element is missing the 'key' prop?

n179911a
  • 125
  • 1
  • 8
  • Does this answer your question? [Can I add a key prop to a React fragment?](https://stackoverflow.com/questions/59390955/can-i-add-a-key-prop-to-a-react-fragment) – Rafael Tavares Apr 08 '22 at 20:21

2 Answers2

0

The key has to be an attribute of the root element returned in the map.

Try writing this code block:

<div className="App">
    {data.map((category) => {
        return (
            <>
                <Label key={category.key}>{category.key}</Label>
            </>
        );
    }
    )}
</div>

like this instead

<div className="App">
    {data.map((category) => {
        return (
            <Label key={category.key}>{category.key}</Label>
        );
    }
    )}
</div>

You could also write:

<div className="App">
    {data.map((category) => {
        return (
            <div key={category.key}>
                <Label>{category.key}</Label>
            </div>
        );
    }
    )}
</div>
vantaboard
  • 56
  • 1
  • 6
0

Answer for when you want/need to keep the Fragment:

The key has to be on the element returned by the .map, not a nested element. A React Fragment is also an element, so the key should be on the Fragment. The shorthand <> doesn't support a key, so you need to use the longer syntax:

<React.Fragment key={key}>
  ...
</React.Fragment>
Jakub Kotrs
  • 5,823
  • 1
  • 14
  • 30