I have been working on react for more than an year now. I have mostly played with iterating an array using .map, .forEach, .filter or using Object.keys and Object.values if it is an object.
But what are the different ways to add a unique key to jsx element. Below is what I have been used to till now
Using unique id from data as key to key prop:
const data= [{"id": "01", "name": "abc"}, {"id": "02", "name": "xyz"}];
render(){
const items = data.map(item => {
return <span key={item.id}>{item.name}</span>;
}
return(
<div>
{items}
</div>
)
}
Using index as key to key prop:
const data= [{"id": "01", "name": "abc"}, {"id": "02", "name": "xyz"}];
render(){
const items = data.map((item, i) => {
let keyValue = i+1;
return <span key={keyValue}>{item.name}</span>;
}
return(
<div>
{items}
</div>
)
}
Is there any other ways to add a unique key to the jsx element apart from what I have mentioned above and which is most efficient and recommended?
from Different ways to add a key to JSX element in loop in React
No comments:
Post a Comment