Reputation: 858
Rookie question, but i'm new to react and i want to loop the value from my state in the render method.
My current (working) code:
render() {
return (
<div>
<div className="status">{status}</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 would love something like:
render() {
return (
<div>
<div className="status">{status}</div>
for (var i = 0; i < this.state.squares; i++) {
if (i!=0 && i % 3 == 0) {
<div className="board-row">
}
{this.renderSquare(i)}
if (i!=0 && i % 3 == 0) {
</div>
}
}
</div>
);
}
Obivously this syntax does not work, but hopefully you get the gist.
Upvotes: 0
Views: 132
Reputation: 363
The way to loop over in the render function is by using map.
render() {
return (
<div>
<div className="status">{status}</div>
{
this.state.squares.map((square, idx) =>
idx % 3 === 0 ?
<div className="board-row" key={idx}>
{this.renderSquare(idx)}
// This makes sure no extra elements are created.
{this.state.squares[idx + 1] && this.renderSquare(idx + 1)}
{this.state.squares[idx + 2] && this.renderSquare(idx + 2)}
</div>
:
null
)}}
);
}
Upvotes: 1
Reputation: 1672
Assuming, ReactJS v16.0.0+, you could do something like:
renderSquareWithWrapper(index){
const inclWrapper = (index != 0 && index%3 ==0);
return (
<React.Fragment>
{ inclWrapper
? <div key={index} className="board-row">{ this.renderSquare(index) }</div>
: this.renderSquare(index)
}
</React.Fragment>,
);
}
render() {
return (
<div>
<div className="status">{ status }</div>
{ Array.isArray(this.state.squares)
&& this.state.squares.map( (_, idx) => this.renderSquareWithWrapper(idx) ) }
</div>
);
}
Don't forget to ensure you add "key" props to your renderSquare
element otherwise you will get a React warning (it's how it identifies -- internally -- each component). The above example leverages Content Fragments which were introduced in ReactJS 16+
Upvotes: 0