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?

3
  • This approach is the same as using bare index. You are just fooling linter. Key should be something related to the item not to its position in array. Commented Jun 5, 2020 at 10:21
  • But is there any problem, like I am using a 'transaction' which is unique right? Commented Jun 5, 2020 at 10:29
  • There might be a problem if at some point you need to insert something in the middle of the array. Commented Jun 5, 2020 at 10:44

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

why can't I cannot use {transaction-{index}}, if array changing ?
I've mentioned above , If the array won't change it's fine to use {transaction-{index}}
Yeah, that I got, but my concern is what if I am mutating the array? why this method is not recommendable?
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.
dev.to/jtonzing/… maybe this article may help you.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.