phantom phantom - 2 months ago 6
React JSX Question

react - MAP through an array contained in another array

I am looping through an array in react using

.map
. However, this array contains another array, which I am unsure of how to loop through.

The code I currently have looks like the below. The result I am looking for is that I get the first image from each of the images array.

//RETURNED FROM AJAX CALL
[
{
id:"1",
images:['image1', 'image2', 'image3']
},
{
id:"2",
images:['image4', 'image5', 'image6']
}
];


REACT CODE

var App = React.createClass({
getInitialState: function() {
return {data: []}
},

componentDidMount: function(){
this.getData();
},

getData: function() {
$.ajax({
url:'.....',
method: 'GET',
success: function(response){
this.setState({data: response});
}.bind(this)
})
},

render: function(){
return(<List images={this.state.data} />)
}
});

var List = React.createClass({

render: function() {
var images = this.props.images.map(function(image){
//want to return the first image from each images array..
})
return(
<div>
<p>{images}</p>
</div>
)
}
});

Answer

Just get first element from property images,

var List = React.createClass({
  render: function() {
    var images = this.props.images.map(function(item) {
      return item.images[0]; 
                        ^^^
    });

    return <div>{ images }</div>       
  }
});

Example

Comments