EDIT: After more testing it appears the error comes from the parent component to this one, which is an antd Modal. Furthermore, it seems like the issue comes from something inside the Modal implementation itself, rather than from something in my code.
I have to dynamically render a grid from the contents of an array with Ant Design Grid I’m using the _.map method to do so, which causes the following warning to appear as an error message:
Warning: Each child in a list should have a unique "key" prop.
So far I’ve tried everything I can think of. I’ve started pruning my code until I reached the following, but I still get the same error (or warning, I’m not sure which it is).
function SettingsContent (props) {
const {SettingsA, SettingsB} = props;
return (
<Row gutter={[12,0]}>
<Col span={12}>
<Row>
<Col span={24}>
SETTINGS A
</Col>
</Row>
<Row>
<Col span={24}>
{
SettingsA.map((settingsFile,settingsFileIndex)=>{
return(
<Row key={settingsFileIndex}>
</Row>
)
})
}
</Col>
</Row>
</Col>
</Row>
);
}
It seems to me that the Row/Col components just don’t care about keys (EDIT: meaning that they don’t acknowledge it, not that they don’t need it). Is there anything I can do about it or should I just not use antd Row/Col and use different components for this?
2
Answers
Keys are what React uses to keep track of components in the dom.
From the documentation: https://react.dev/learn/rendering-lists
So, you’re wrong about this:
All list elements should have a key added to them and it sounds like you’ve been creating "lists" of rows and columsn without adding appropriate keys onto them.
I don’t know what’s in your
settingsFileIndex
, but you’re on the right track to setting a unique key for both the rows and column components. You don’t have to switch components, you just need to add unique keys properly.However, it’s worth noting the additional following pitfall noted in the documentation about using an index as the key:
tl;dr: Create unique keys, don’t just use the index.
Keys are needed to make it easier for React DOM to find unique elements. You can add the key like this to parent wrapper: