-1

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?

chylinski
  • 85
  • 12

2 Answers2

5

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

Shri Hari L
  • 4,551
  • 2
  • 6
  • 18
  • great, thanks, it works! but i'm gettig warning "Warning: Each child in a list should have a unique 'key' prop.%s%s See https://reactjs.org/link/warning-keys for more information.%s" ". Where do i put the key and what should it be? – chylinski Sep 15 '22 at 12:19
  • Edited the answer. Basically whenever you are rendering an array of elements, you have to pass `key` to every child. – Shri Hari L Sep 16 '22 at 04:52
  • done that, but the warning didn't disappear. – chylinski Sep 16 '22 at 21:31
0

Try below code:

const array = [
    {
        className: "board-row",
        squares: [2, 4, 6]
    },
    {
        className: "board-row",
        squares: [1, 2, 3]
    }
]

return (
    <div>
        {array.map((item, index) => {
            return (
                <div key={index} className={item.className}>
                    {item.squares.map((square, indexSquare) => {
                        return square;
                    })}
                </div>
            )
        })}
    </div>
)
Hoang Long
  • 446
  • 4
  • 5