Skip to content Skip to sidebar Skip to footer

Is It Better To Use Index As Key Instead Of Math.random() In React?

Following is my react code, which is displaying menu items and unfortunately I am not getting any id to add as a key in list. As mentioned in the docs under Keys section, it is ad

Solution 1:

To put it simply I wouldn't use either. The point of the key is to allow React identify the children <li>s you are creating, during render.

Using the a random key or array index will not provide a consistent key.

I'd instead add an ID to each of your objects...

[
  { id: 1, name: 'Home' },
  { id: 2, name: 'About' },
  { id: 3, name: 'News' },
  { id: 4, name: 'Contact' },
].map(({ id, name }) => {
  return <li key={id}>{name}</li>
})

That way if your were to reorder the array, the ID consistently identifies the object.


Post a Comment for "Is It Better To Use Index As Key Instead Of Math.random() In React?"