Single React "key" problem

Asked

Viewed 47 times

2

I am trying to create a chess game using React. I am doing very well except for this mistake. This is my code:

import "./style.css";

function App() {

  const squares = []; //squares order

  for (var i=0; i<8; i++) {

  for (var j=0; j<8; j=j+2) { //appending squares rows starting with a white square
    squares.push('sqr w')
    squares.push('sqr b')
  }

  for (var h=0; h<8; h=h+2) { //appending squares rows starting with a black square
    squares.push('sqr b')
    squares.push('sqr w')
  }}

//create square component
  const squareItem = squares.map(square => {
    return (
      <div className={square}/>
    )
  })

  return (
    <div className="tab">
        {squareItem}
    </div>
  );
}

export default App;

The error message is this: Warning: Each Child in a list shoud have a Unique "key" prop

What I do?

1 answer

1


To summarize, React asks for a prop to be passed key for any component that is within a list.

According to React’s own documentation

Keys help React identify which items have been changed, added, or removed. Keys must be assigned to the elements within the array to give a stable identity to the elements:

in your case just do it this way:

const squareItem = squares.map((square, index) => {
    return (
      <div key={index} className={square}/>
    )
  })

References:

Lists and Keys - React

Browser other questions tagged

You are not signed in. Login or sign up in order to post.