john doe john doe - 1 month ago 17
React JSX Question

Create html in reactjs using nested for loops.

I want to create nested elements in react js but following does not seem to work.

var allSeats = [];
for( let i = 0 ; i<5 ; i++ ) {
allSeats.push( <div className="each-row"> );
for( let j=0; j<2 ; j++ ) {
allSeats.push( <div className="each-seat">hei</div> );
}
allSeats.push( </div> );
}

return (
<div className="theater">
{allSeats}
</div>
);


What's wrong with the above code?

Answer

Piotr is right - much better to split your code to components. But just in case, here's fixed snippet like you have:

var rows = [];

    for(let i=0; i<5; i++) {
        var seats = [];

    for(let j=0; j<2; j++) {
        seats = seats.concat(<div className="seat"></div>);
    }

    rows = rows.concat(<div className="row">{seats}</div>);
}

return (
    <div className="theater">
        {rows}
    </div>
);