Reputation: 439
When an array of children are passed as prop and looped over to render in parent component, react is complaining about missing unique key identifier on array iteration.
What is the correct way to overcome the warning?
Can I pass key along with children under prop.
If I want to set key to children while rendering in parent, it is complaining child's key prop is read only.
Upvotes: 5
Views: 17023
Reputation: 6944
Would be easier if you shared some code.
You shouldn't need to iterate the children to render then, unless you are augmenting them in some way.
class MyComponent extends React.Component {
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
If you must, can you wrap them in a div
and apply the key to that instead?
class MyComponent extends React.Component {
render() {
return (
<div>
{this.props.children.map((child, index) => (<div key={index}>{child}</div>))}
</div>
)
}
}
I haven't tried this but you might be able to clone the element and change the key
class MyComponent extends React.Component {
render() {
return (
<div>
{this.props.children.map((child, index) => {React.cloneElement(child, {key: index})})}
</div>
)
}
}
Upvotes: 7