Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript syntax in ReactJS

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

, 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.

enter image description here

>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>
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading