I have a ReactJS render function where I iterate over an array to display the contents like this:
render() {
let object = eval('('+this.props.objectData+')');
let cd = object.objColAliases;
return (
<div>
{
cd.map(o=>{
return <p>{o}</p>
})
}
</div>
);
}
This code is working but at the console I have an warning:
react-jsx-dev-runtime.development.js:87 Warning: Each child in a list
should have a unique "key" prop.
, the warning makes sense, map is used to iterate over Maps not over simple arrays.
So I try to iterate like a normal array, like this:
render() {
let object = eval('('+this.props.objectData+')');
let cd = object.objColAliases;
return (
<div>
{
for (let i = 0; i < cd.length; i++) {
return <p>{o}</p>
}
}
</div>
);
}
But now I have a syntax error on the line with "for (let i = 0; i < cd.length; i++)".
How do I write the correct code in this context?
This is a sandbox with the problem.
>Solution :
You need to provide a unique key tag to elements returned inside the .map, s
render() {
let object = eval('('+this.props.objectData+')');
let cd = object.objColAliases;
return (
<div>
{
cd.map(o=>{
return <p key={o.id}>{o}</p>
})
}
</div>
);
}
If o does not have a unique property, you can also use the index, like so
render() {
let object = eval('('+this.props.objectData+')');
let cd = object.objColAliases;
return (
<div>
{
cd.map((o, index) =>{
return <p key={index}>{o}</p>
})
}
</div>
);
}
