Reputation: 3807
I have a simple component Movies.jsx and array of objects inside movieList.jsx I am exporting this array and setting the state inside Movies.jsx equal to that array. When I look in the console i see that it got passed to the state ok.
I wanna iterate through that array of object and render it: How do I do that? Whatever I try i get an error "Objects are not valid as a React child"
Before I turned it into array it was a json object but I didn't have look with that either.
I am also getting an error that "Each child in an array or iterator should have a unique 'key' prop"
Example 2: How would it be if instead of array it was JSON object. Would we also need to export it from seperate component and then require? How would we iterate through it?
Upvotes: 0
Views: 744
Reputation: 5594
Here's a quick example of what you're trying to achieve. Since you provided screenshots, I had to provide make-shift data.
var Movies = {
"data": [{
"id": 1,
"name": "Forest Gump",
"rating": 5
}, {
"id": 2,
"name": "Lion",
"rating": 5
}]
};
var Movie = React.createClass({
render: function() {
return (
<div>
<div>Name: {this.props.item.name}</div>
<div>Rating: {this.props.item.rating}</div>
</div>
);
}
});
var MovieContainer = React.createClass({
getInitialState() {
return {
movies: null
};
},
componentWillMount: function() {
this.setState({
movies: Movies.data
})
},
render: function() {
return (
<div>
{ this.state.movies.map(function(item) {
return (
<Movie key={item.id} item={ item } />
)
}) }
</div>
);
}
});
ReactDOM.render(
<MovieContainer />,
document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<div id="container"></div>
Upvotes: 2
Reputation: 211
Check out the React docs - https://facebook.github.io/react/docs/lists-and-keys.html#keys and https://facebook.github.io/react/docs/lists-and-keys.html#embedding-map-in-jsx. You need to set unique key for each item rendered in map function. This way react can distinguish them.
Upvotes: 0