Skip to content

Loop inside React JSX

Learn how to loop in React JSX where ObjectRow is a separate component. A simple for loop is not valid in JSX because JSX maps to function calls.

One way to do this is create an array and insert ObjectRow() components into the array and return it.

var rows = [];
for (var i = 0; i < nrows; i++) {
    rows.push(ObjectRow());
}

return tbody(rows);

You can follow the same method to add a component multiple times from another component.

class Multiple extends React.Component {
  render() {
    let rows = [];
    for (let i=0; i < 4; i++) {
      rows.push(<HeyHello key={i} />)
    }
    return <h1>{rows}</h1>;
  }

To map an array of employee names from the employee JSON, you can do map to loop over.

var employees = [{
	"Name": "Anand",
	"ID": "A616"
}, {
	"Name": "Baskar",
	"ID": "B717"
}, {
	"Name": "Naveen",
	"ID": "N98"
}, {
	"Name": "Arthi",
	"ID": "R676"
}]
<ul>
{
  employees.map((employees) => {
    return (
        <li>
          {employees.Name}
        </li>
    );
  })
}
</ul>

Similar example with ObjectRow.

Multiple extends React.Component {
	render() {
    let rows = [];
    for (let i=0; i < 4; i++) {
      rows.push(your_object);
    }
    return <h1>
             { rows.map((object, i) => <ObjectRow obj={object} key={i}/>) }
           </h1>
	}
See also  Warning: Each child in a list should have a unique "key" prop - How to fix this react error?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.