Kharrid
Kharrid

Reputation: 71

Is there a better way to loop through data in the render section of React?

I am looking to loop through data, call a function, and return the results so they can be posted in the render section of React. I am new to the language and was trying to implement an extra feature in the main React tutorial.

I'm trying to make the render section look like the following:

    <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>

The task is to use two loops to create the above structure. This is my code:

  const board = [0, 1, 2].map((num) => {

    const row = Array(3);
    for (let i of [0, 1, 2]) {
      row[i] = this.renderSquare(num*3 + i);
    }

    const board_row = row.map(num2 => {
      return (
        num2
      )
    })

    return (
      <div className="board-row">
        {board_row}
      </div>
    );
  });

I think the board_row variable is wasteful because it does a whole map operation just to format the row properly. When I try to move the for loop into the map operation, I can't find a way to pass num into the map operation.

  const board = [0, 1, 2].map((num) => {

    const board_row = [0, 1, 2].map(num2 => {
      // How do I get num here?
      return this.renderSquare(num*3 + num2);
    })

    return (
      <div className="board-row">
        {board_row}
      </div>
    );
  });

How do I do this properly?

Upvotes: 1

Views: 58

Answers (2)

symlink
symlink

Reputation: 12209

I'm a little rusty with React so you may need to tweak this a bit:

let result
return Array(9).map((el,idx) => {
    if(!idx % 3){
        result += <div className="board-row">
    }
    result += {this.renderSquare(idx)}
    if(!(idx-2) % 3){
        result += </div>
    }

    return result
})

Upvotes: 0

Quantumass
Quantumass

Reputation: 836

You can do it like that since you can't left a tag opened until the next iteration

return (
    <div>
      {
        [0,3,6].map(num => (
            <div className="board-row">
              {
                Array(3).fill().map(
                  (_, index) => this.renderSquare(index + num)
                )
              }
            </div>
          ))
      }
    </div>
  );

Upvotes: 2

Related Questions