I am new to Javascript and React and have a similar question as this one:
I am following the tutorial for the tic-tac-toe game and am trying to understand mixing JSX and loops and arrays.
I have this which is working:
class Board extends React.Component {
renderSquare(i) {
return (
<Square
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
/>
)
}
renderRow(row) {
let ss = [];
for(let i=0; i<3; i++)
{
ss.push(this.renderSquare(i+row));
}
return (
<div className="board-row">
{ss}
</div>
)
}
renderBoard() {
let board = []
for(let i=0; i<3; i++)
{
board.push(this.renderRow(i*3));
}
return board;
}
render() {
return (
<div>
{this.renderBoard()}
</div>
)
}
}
Basically the idea is to replace the hard coded board which was done with this:
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>
);
}
What I'd like to do is effectively combine renderRow and renderBoard together in some kind of nested for loop structure. I only have the different functions at all because I don't know how to inline the nested structure of the elements to the array that I am making. Is this possible?
for
loops. Alsofor
loops don't play well with jsx and most of the time I find them hard to read. I try to avoid them as much as possible. Actually I haven't used one even a single time while creating react components all day long in a medium sized project for months. I usemap()
whenever possible (which is in 99% of the cases).