Search code examples
javascriptreactjsnested-loops

nested for loop in react render


The site is telling me there are many similar questions, but i just couldn't find an answer i'm looking for. I believe it should be an easy one for react pros, as i'm a beginner.

I've got this code inside render function:

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

And i want to rewrite it using two nested loops, all I could come up with is this (doesn't work, i try to correct errors, but that just brings me to fresh errors):

return (
  <div>
   {for (let j = 0; j < 3; j++) {
      <div className="board-row">
       {for (let k = 0; k < 3; k++) {
         {this.renderSquare((j*3) + k)}
       }}
      </div>
   }}
  </div>

);

How do i rewrite this code?


Solution

  • There are lot of workaround for making it work, like this

    My suggestion would be have a good data structure for it.

    const board = [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    
    return (
      <div>
       {board.map((row, i) => (
          <div key={i} className="board-row">
           {row.map(square => renderSquare(square))}
          </div> 
       ))}
      </div>
    )
    

    and you cannot use for loop inside the render method. You should use .map for it.

    Whenever you are rendering an array of elements, don't forget the keys.

    Read more: https://reactjs.org/docs/lists-and-keys.html#keys