Reputation: 816
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?
Upvotes: 0
Views: 191
Reputation: 546
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>
);
Upvotes: 1
Reputation: 7468
As Fabian noted - JSX elements must be closed:
All tags must be closed, either with the self-closing format or with a corresponding closing tag https://facebook.github.io/react/tips/self-closing-tag.html
Would splitting into components work for your intended use? Demo here: http://codepen.io/PiotrBerebecki/pen/ALabXK
class Rows extends React.Component {
render() {
var allRows = [];
for( let i = 0 ; i<5 ; i++ ) {
allRows.push( <div className="each-row">Row<Seats /></div> );
}
return (
<div className="theater">
{allRows}
</div>
);
}
}
class Seats extends React.Component {
render() {
var allSeats = [];
for( let j=0; j<2 ; j++ ) {
allSeats.push( <div className="each-seat">Seat</div> );
}
return (
<div className="seats">
<b>{allSeats}</b>
</div>
);
}
}
ReactDOM.render(
<Rows />,
document.getElementById('app')
);
Upvotes: 1