Reputation: 155
Completely new to React. In the react tic-tac-toe tutorial, they make a 3x3 hard coded grid with this code:
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>
);
}
Is it possible to create a grid based on a gridSize passed into props such that the entire code in render() is a loop? Something like:
render() {
return (
<div>
for (let row=0; row<props.gridSize; row++) {
<BoardRow rowIndex=row cols=gridSize> (how to pass two parameters to BoardRow?)
}
</div>
);
}
Upvotes: 0
Views: 495
Reputation: 371049
With a couple of Array.from
s to create new arrays from a given length, you can multiply the outer index (0 to 2) by 3 and add it to the inner index (0 to 2).
render() {
return (
<div>{
Array.from({ length: 3 }, (_, i) => (
<div className="board-row">{
Array.from({ length: 3 }, (_, j) => (
this.renderSquare((i * 3) + j)
))
}</div>
))
}</div>
);
}
Upvotes: 1