React Tic Tac Toe: unique key warning

Hi campers!

I am new to React and is doing the Tic Tac Toe tutorial from React website to learn it.

I encounter a “Warning: Each child in a list should have a unique “key” prop.” problem when implementing the third additional feature, which is rewrite line 27 to 45 in https://github.com/ming-yong/react-tic-tac-toe/blob/master/src/index.js with 2 for loops.

This is what I have so far:

class Board extends React.Component {
	renderSquare(i) {
		return <Square key={i} value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />;
	}

	createBoardOfSquares = () => {
		let boardOfSquares = [];
		let index = 0;
		//outer loop to create parent
		for (let row = 0; row < 3; row++) {
			let rowOfColumns = [];
			//inner loop to create children
			for (let col = 0; col < 3; col++) {
				rowOfColumns.push(this.renderSquare(index));
				index++;
			}
			boardOfSquares.push(<div className="board-row">{rowOfColumns}</div>);
		}
		return boardOfSquares;
	};

	render() {
		return <div>{this.createBoardOfSquares()}</div>;
	}
}

I’ve tried using the index i (I have read about you shouldn’t use index as keys but I figure in this case it will be fine), and key={this.props.squares[i]+i} but neither of these works. Can you give me some direction?

Does it say what line is the problem? It’s possible that this line is actually the problem:

React usually wants all the children to have a key, and this line may be one of them.

1 Like

I think you are right!

This is the warning:

And the first line is the line you are pointing to! I will try giving the div a key instead!

Update: Problem solved! Thanks a lot!

1 Like