1

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?

Rahul N R
  • 23
  • 1
  • 4

2 Answers2

2

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

hendrixchord
  • 4,662
  • 4
  • 25
  • 39
  • why can't I cannot use {`transaction-{index}`}, if array changing ? – Rahul N R Jun 05 '20 at 10:36
  • I've mentioned above , If the array won't change it's fine to use `{transaction-{index}}` – hendrixchord Jun 05 '20 at 10:37
  • Yeah, that I got, but my concern is what if I am mutating the array? why this method is not recommendable? – Rahul N R Jun 05 '20 at 10:39
  • Then react won't know what DOM elements to re-render & what not to, keys are way for React to identity that with the virtual DOM. If there are duplicate keys then it will only render the first item and won't render the remaining duplicate items. – hendrixchord Jun 05 '20 at 10:41
  • https://dev.to/jtonzing/the-significance-of-react-keys---a-visual-explanation--56l7 maybe this article may help you. – hendrixchord Jun 05 '20 at 10:44
0

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.

Dostonbek Oripjonov
  • 1,508
  • 1
  • 12
  • 28