Skip to content

Reactjs: Arrays in jsx

When I tried out Reactjs tutorial few months ago, I noticed that in the official starter code, they repeated same div elements in the render() method, just in case of change in the source, I will list it here:

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

From the fist look I did not like the repetition, even for a beginner in React, javascript basic array operations should be a familiar topic.

So I refactored that section using the map operation:

render() {
    return (
      <div>
        {[0, 3, 6].map(j => (
          <div key={j} className="board-row">
            {[j, j + 1, j + 2].map(
                i => this.renderSquare(i)
            )}
          </div>
        ))}
      </div>
    );
  }

This is not so complicated for any React beginner, and using similar concise code beats repeating the same function calls or elements over and over again.

What do you think?

Go to Top