Reputation: 1240
What is the best way to define "KEY" in React when creating a list with map function from an array which containing no unique ID or any unique fields. I don't want to go with index because If later any item remove or added in array previous array index will be change that does not helps React to keep track listing DOM nodes. So how can I generate or define "KEY"(unique KEY) for DOM nodes?
Upvotes: 0
Views: 241
Reputation: 2860
What not to do
You should not be using index of the map for you Key, its an anti-pattern, it may lead to unpredictable results.
Please check this https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
Right approach
You should be using proper unique-id for your Key, like a DB id or some unique-id.
This Key is used internally to identify the DOM elements to render and not to render again.
Upvotes: 1
Reputation: 4011
If possible, convert it to an array of objects and have one of the key/value pairs be the id... Here is a little helper function to generate random ids:
const generateId = () => Math.random().toString(36).substr(2, 10)
Then use this function something like this:
const arr = [{ id: generateId(), name: 'Bob' }, { id: generateId(), name: 'Jane' }, { id: generateId(), name: 'Jack' }]
Upvotes: 1