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?
CodePudding user response:
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>
CodePudding user response:
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>