0

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?

2
  • allSeats.push( </div> ); this is not a valid JSX element. It always needs an opening and closing tag. You will have to find another approach for this. Commented Oct 11, 2016 at 14:34
  • @FabianSchultz How can this be approached then? Commented Oct 11, 2016 at 14:35

2 Answers 2

1

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>
);
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.