Unique keys via id in React
In the code above, we added the ordinal number of the element in the array to the key attribute. In fact, this is a bad practice and should only be used as a last resort.
The thing is that when sorting the array, the elements will have different keys and React will not be able to correctly track the relationship between the array elements and the corresponding tags.
A better practice would be to add a unique identifier to each product, which will be used as a key.
Let's add a property id with the number of our product to each product in our array:
const prods = [
{id: 1, name: 'product1', cost: 100},
{id: 2, name: 'product2', cost: 200},
{id: 3, name: 'product3', cost: 300},
];
Now we use this id as a key:
function App() {
const res = prods.map(function(item) {
return <p key={item.id}>
<span>{item.name}</span>:
<span>{item.cost}</span>
</p>;
});
return <div>
{res}
</div>;
}
Modify the previous task by adding id to the array and using them as values for the key attribute.