Aanchal Adhikari Aanchal Adhikari - 8 months ago 107
React JSX Question

Implementation of two for loops in React Js to create a 3X3 square marix box for tic-tac-toe

I'm following the React Js tutorial from the official site which helps us build a tic-tac-toe game. The square boxes are created by hardcoding all the squares as follows:

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


}

I managed to shorten the code by using a for loop as shown below:

render(){
let sqrRen = [];
for(let i = 0; i < 9; i=i+3){
sqrRen.push(<div className = "board-row">
{this.renderSquare(0+i)}
{this.renderSquare(1+i)}
{this.renderSquare(2+i)}
</div>);
}
return (
<div>
{sqrRen}
</div>
);


}
But I also want to generate the squares in each row using another for loop as follows:

render(){
let sqrRen = [];
for(let i = 0; i < 9; i=i+3){
sqrRen.push(<div className = "board-row">
{
for(let j=0;j<3;j++){
this.renderSquare(j+i)
}
}
</div>);
}

return (
<div>
{sqrRen}
</div>
);


}
but this is not working. I get the following error:
error snippet

Any suggestions on how to go about using two for loops?

Answer Source

You don't need to use the usual for loops as they look very messy. Instead, you should utilize the new ES6 features and syntax to achieve a cleaner and more understandable approach.

The solution below renders a 3x3 tic-tac-toe board just fine:

import chunk from 'lodash/chunk';

const styles = { width: '40px', height: '40px', float: 'left', textAlign: 'center' };

return (

        <div className="tic-tac-toe-container">
            {chunk(new Array(9).fill(0), 3).map((item, itemIndex) => {
                return (
                    <div key={itemIndex} className="row">
                        {item.map(col => <div className="col" style={styles}>COL</div>)}
                    </div>
                )
            })
            }
        </div>
    );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download