Mixing loops and React JSX

Mixing loops and React JSX

  

I am new to Javascript and React and have a similar question as here:

I am following the tutorial for the tic-tac-toe game and am trying to understand mixing JSX and loops and arrays.

I have this which is working:

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
       value={this.props.squares[i]}
       onClick={() => this.props.onClick(i)}
      />
    )
  }
  renderRow(row) {
    let ss = [];
    for(let i=0; i<3; i++)
    {
      ss.push(this.renderSquare(i+row));
    }
    return (
      <div className="board-row">
      {ss}
      </div>
    )
  }
  renderBoard() {
    let board = []
    for(let i=0; i<3; i++)
    {
      board.push(this.renderRow(i*3));
    }
    return board;

  }
  render() {
    return (
      <div>
        {this.renderBoard()}
      </div>
    )
  }
}

Basically the idea is to replace the hard coded board which was done with this:

>>render() {
  return (
    <div>
      <div className="board-row">
        {this.renderSquare(0)}
        {this.renderSquare(1)}
        {this.renderSquare(2)}
      </div>
      <div className="board-row">
        {this.renderSquare(3)}
        {this.renderSquare(4)}
        {this.renderSquare(5)}
      </div>
      <div className="board-row">
        {this.renderSquare(6)}
        {this.renderSquare(7)}
        {this.renderSquare(8)}
      </div>
    </div>
  );
}

What I'd like to do is effectively combine renderRow and renderBoard together in some kind of nested for loop structure. I only have the different functions at all because I don't know how to inline the nested structure of the elements to the array that I am making. Is this possible?

Answer

What you often see people do is map over some structure in order to dynamically create an array of elements. In your case, since you only have a flat list of squares instead of a proper hierarchy, you could get around by simply creating one temporarily. And then you don’t actually need all those functions.

>>class Board extends React.Component {
    render() {
        const indexes = [[0, 1, 2], [3, 4, 5], [6, 7, 8]];

        return (<div>
            {indexes.map(row =>
                <div class="board-row">
                    {row.map(index =>
                        <Square key={index}
                            value={this.props.squares[index]}
                            onClick={() => this.props.onClick(i)}
                            />
                    )}
                </div>
            )}
        </div>);
    }
}

This is btw. a good example where using hyperscript makes this a bit easier on the eyes, compared to JSX. I don’t want to convert you away from JSX here, but I think all that nesting and those curly braces makes it difficult to follow. If you are interested, take a look at the following snippet that uses hyperscript:

const h = React.createElement;

function Square(props) {
  return h('div', { className: 'square', onClick: props.onClick }, props.value);
}

function Board(props) {
    const indexes = [[0, 1, 2], [3, 4, 5], [6, 7, 8]];
    return h('div', null, indexes.map((row, k) =>
        h('div', { key: k, className: 'board-row' }, row.map(index =>
            h(Square, { key: index, value: props.squares[index], onClick: props.onClick.bind(null, index) } )
        ))
    ));
}


const props = {
  squares: [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ],
  onClick: (i) => console.log(i),
};
ReactDOM.render(h(Board, props), document.getElementById('target'));
>.board-row {
  display: flex;
}
.square {
  width: 40px;
  height: 40px;
  border: 1px solid gray;
}
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="target"></div>

© 2024 Dagalaxy. All rights reserved.