React keys with string and index

4.9k Views Asked by At

As per React docs, they are not recommending to use the key as an index. but is there any issue with using the index and a string value. like below one,


transactionDetail.map((item,index) => <div key={`transaction-{index}`}>{trName}</div>)

is there any issue with using like this?

2

There are 2 best solutions below

5
On BEST ANSWER

Unless you're not going to be mutating the array i.e. transactionDetail & the order of the array won't change on every re-render it's fine to use index as a key.

Else if it is going change or you'll be mutating it then you should use some value unique to each item inside transactionDetail

0
On

So, I think there is no problem if there are no other element with same index. Because, key is used by virtual-dom to define elements which have changed to re-render component. It may produce problem if there are elements with same index.