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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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>
Method 2
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>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0