1

A common pattern is generating react elements from array. In case of iterating over react components are there any cases where should/can ignore key prop warning?

Like can we ignore in case of element rendering static text etc? Note: After rendering my elements aren't going to change, add new or remove.

const days = ['Sunday' 'Mon.........,,, 'Saturday'];

days.map(day => <div>{day}</div>);
A dev
  • 930
  • 3
  • 12
  • 27
  • 1
    Possible duplicate of [Disable / workaround React key requirement?](https://stackoverflow.com/questions/41974428/disable-workaround-react-key-requirement) – Ashniu123 Oct 09 '18 at 11:56
  • @Ashniu123, I am not asking for workaround or disabling it. Please review my comment for Jo Peyer's answer. – A dev Oct 09 '18 at 13:26

1 Answers1

-1

You shouldn't be ignoring this warning.

Have a read of the doc: https://reactjs.org/docs/lists-and-keys.html#keys

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

If you truely don't have any key like value to use, you can use the index of the array (assuming its coming from a statically ordered source) so that react can use the keys to identity what has changed.

const myArray = ["Some", "Static", "Stuff"]

const MyComponent = () => (
  <div>
    {myArray.map((item, i) => <div key={i}>{item}</div>)}
  </div>
)
Jo Peyper
  • 390
  • 1
  • 10
  • 1
    So basically my question is, if after rendering my items aren't changing, adding or removed, in that case also is it required to use keys? – A dev Oct 09 '18 at 13:22
  • without the keys, I would make no guarantee that renders triggered by other components in the tree wont have weird results in the dom. These keys are used by react to keep track of things between the virtual dom and the real dom... and relatively cheap to add so I guess my question would be "why not add the keys?" – Jo Peyper Oct 09 '18 at 13:34
  • This doesn't answer the question at all. Keys in react are just an optimization. Even if the code *is* changing the order of elements, you don't need to use keys. – mauroc8 May 19 '23 at 17:40
  • "why not add the keys?" because maybe you're calling functions and you don't want to be passing the `key` as an argument if it's not necessary – mauroc8 May 19 '23 at 17:45