0

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"

enter image description here

enter image description here

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?

enter image description here

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Win. That worked beautiful. Can you please just update the answer and tell me if instead of the provided array it was the JSON object in question. Also in a separate component. Example is in my question above. Would I also need to export it or is require enough.
@Igor-Vuk Updated my answer.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.