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'));
}
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>
}
});