Zaid Humayun Zaid Humayun - 1 month ago 8
Javascript Question

Creating a JSX list in React with an object

So, I know when creating lists of data in React, you usually use the map function. But, since that works only for arrays, and I have an object, I'm not sure how to go about this.

So, I have the following object

[Object, Object, Object]
0:Object
1:Object
2:Object
length:3
__proto__:Array[0]


I'm trying to render the image from the url contained within each of these objects, and here is how I am trying to do it.

import React from 'react';

const EvolutionChainComponent = ({data}) => {
console.log(data);
for(let key in data){
console.log(data[key]);
return(
<div>
<img src={data[key].sprites.front_default} role='presentation'/>
</div>
)
}
}

export default EvolutionChainComponent;


The problem is that since I am using a for in loop, once I return the div, the code breaks out of the loop. I'm sure there is a simple way to do this by iterating over an object, but I'm not quite sure what that is since I've only ever seen React data iteration used with the map function on an array.

Answer

No need to iterate over the object, You need to use the simple map method to loop over the array of objects

import React from 'react';

const EvolutionChainComponent = ({data}) => {
    console.log(data);
    data.map(function(item){
       return(
            <div>
                <img src={item.sprites.front_default} role='presentation'/>
            </div>
        )
    })

}

export default EvolutionChainComponent;