ReactJS - "Keys" error when adding components in loops -
i following tutorial on how build react tic tac toe example, , found interesting.
at end of tutorial, found 1 of following challenges:
rewrite board use 2 loops make squares instead of hard coding them.
this original render
method
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 first did 1 loop , working great
render() { let col_count = 3; let row_count = 3; let rows = []; (var = 0; < row_count; i++) { rows.push( <div key={i} classname="board-row"> {this.rendersquare(i*col_count + 0)} {this.rendersquare(i*col_count + 1)} {this.rendersquare(i*col_count + 2)} </div> ); } return ( <div>{rows}</div> ); }
but tried code 2 loops:
render() { let col_count = 3; let row_count = 3; let rows = []; (var = 0; < row_count; i++) { let cols = []; (var j = 0; j < col_count; j++) { cols.push(this.rendersquare(i*col_count + j)); } rows.push( <div key={i} classname="board-row">{cols}</div> ); } return ( <div>{rows}</div> ); }
and started getting famous "keys" error on console:
warning: each child in array or iterator should have unique "key" prop. check render method of
board
.
so wonder: missing? rows have still valid key id working when using 1 loop. , columns inside each row come render method has worked.
where problem second implementation? how implement not error?
update:
in case needed, rendersquare
rendersquare(i) { return ( <square value={this.props.squares[i]} onclick={() => this.props.onclick(i)} /> ); }
i think <square />
components need keys.
rendersquare(i) { return ( <square key={i} value={this.props.squares[i]} onclick={() => this.props.onclick(i)} /> ); }
Comments
Post a Comment