Rahul N R
Rahul N R

Reputation: 23

React keys with string and index

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?

Upvotes: 1

Views: 5408

Answers (2)

hendrixchord
hendrixchord

Reputation: 5434

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

Upvotes: 2

Dostonbek Oripjonov
Dostonbek Oripjonov

Reputation: 1674

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.

Upvotes: 0

Related Questions