Suppose I have this array:
[
{ label: 'Something', value: 4815 },
{ label: 'Another', value: 1623 },
{ label: 'Else', value: 4248 },
{ label: 'Whatever', value: 1516 },
{ label: 'Something', value: 2342 },
{ label: 'Yep', value: 4815 }
]
If I do arr.map(item => (<div key={item.label}>...</div>)) then the key will be repeated. I know the ideal scenario would be that the data has ids, but supposing it doesn't have, is it a good idea to do something like:
arr.map((item, index) => (<div key={`${item.label}-${index}`}>...</div>))
CodePudding user response:
It is not recommended if the order of the array may change, which in turn can affect the performance of the app. Giving the object items unique keys can solve this issue in your case. ex)
{ label: 'Something', value: 4815, key: '...' },
CodePudding user response:
If the order of the items don't change I suppose you can use them. From the docs:
We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.
