1

I have a json file with an array of data representing people.

I want to make a component per person. Should I make a component and loop through my data inside my render function or should I loop outside my ReactDOM.render function and pass in a specific piece of data each loop?

Should I do it this way:

var PersonBox = React.createClass({
  render: function() {
    var person = this.props.data.map(function(person, index) {
          return <div id="person" key={index}>
                 // person stuff here
                  </div>
        });
        return (
                <div>
                  {person}
                </div>
              );
  }

ReactDOM.render(<PersonBox data={mydata} />, document.getElementById('container'));

Or should I do this:

var PersonBox = React.createClass({
  render: function() {
        return (
                <div>
                  // person stuff
                </div>
              );
  }  

mydata.map(function(person, index) {
        ReactDOM.render(<PersonBox data={person} />, document.getElementById('container'));
}

1 Answer 1

1

You should use first variant., you can split your code to small components, for example you can split your code to two components like so

var Person = React.createClass({
  render: function() {
    return <div>
      Name is <strong>{ this.props.name }</strong>
    </div>
  }
});

var PersonBox = React.createClass({
  render: function() {
    var people = this.props.data.map(function(person, index) {
      return <Person key={ index } name={ person.name } />  
    });

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

Example

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.