Guilherme
Guilherme

Reputation: 325

Looping with useState gets and unique key error

I'm doing a add multiple items to render in my browser, but when i click addItem the item renders but i get this error message:

'Warning: Each child in a list should have a unique "key" prop.'

enter image description here

const newItem: React.FC = () => {
  const [state, setState]: any = useState([]);

  function addItem() {
    setState([
      ...state,
      <div>
        This is a Test
      </div>,
    ]);
  }
  return (
    <>
      <AllBets>
        {state.map((item: any) => (
          <BetsRange key={item.id} id={'div-parent'}>
            {item}
          </BetsRange>
        )
        )}
      </AllBets>
      <AddItem onClick={addItem}>
      </AddItem >
    </>
  )
}

Upvotes: 1

Views: 185

Answers (1)

Mario Petrovic
Mario Petrovic

Reputation: 8332

You left out fragment element that wraps your two elements, and it would not work at all, but I edited it anyways.

As far as the error goes, you get that error only if that item.id is the same for two or more elements.

If you are not sure what element is that, you can add one more guarantee that you will not get this error. Just add index as concatted string to id: key={`${item.id}${index}`}

const newItem: React.FC = () => {
  const [state, setState]: any = useState([]);

  function addItem() {
    setState([
      ...state,
      <div>
        This is a Test
      </div>,
    ]);
  }
  return (
    <>
      <AllBets>
        {state.map((item: any, index) => (
          <BetsRange key={`${item.id}${index}`} id={'div-parent'}>
            {item}
          </BetsRange>
        )
        )}
      </AllBets>
      <AddItem onClick={addItem}>
      </AddItem >
    </>
  )
}

Upvotes: 1

Related Questions