I have values in an array object called farms. In this case, we are using the farms.map function. However, this warning occurred, and when I searched the documentation, it was telling me to write a unique value for key.
Warning: Each child in a list should have a unique "key" prop. in React native?
So I wrote v.placeId in the key in the TargetCon component, but the warning was not resolved. How do I fix it?
this is my code
farms = [
{
placeId: 272,
name: 'hamburger',
},
{
placeId: 273,
name: 'coffee',
},
];
const TargetFarm = () => {
const {farms} = useSelector((state: RootState) => state.post);
return (
<SeCotainer platform={tablet}>
{farms.map(v => {
return (
<>
<TargetCon key={v.placeId.toString()}>
<TargetTxt platform={tablet}>{v.name}</TargetTxt>
</TargetCon>
</>
);
})}
</SeCotainer>
);
};
export default TargetFarm;
CodePudding user response:
Add the key attribute in root element within the loop
return (
<React.Fragment key={v.placeId.toString()}>
<TargetCon>
<TargetTxt platform={tablet}>{v.name}</TargetTxt>
</TargetCon>
</React.Fragment>
);
CodePudding user response:
You can use index
inside map() Function
return (
<SeCotainer platform={tablet}>
{farms.map((v, index) => {
return (
<React.Fragment key={`targetcon_${index}`}>
<TargetCon key={v.placeId.toString()}>
<TargetTxt platform={tablet}>{v.name}</TargetTxt>
</TargetCon>
</React.Fragment>
);
})}
</SeCotainer>
);
CodePudding user response:
In the above code, you have converted the value of the key into a string that wouldn't work
Refer to the below code I have made the changes:
farms = [
{
placeId: 272,
name: 'hamburger',
},
{
placeId: 273,
name: 'coffee',
},
];
const TargetFarm = () => {
const {farms} = useSelector((state: RootState) => state.post);
return (
<SeCotainer platform={tablet}>
{farms.map(v => {
return (
<>
<TargetCon key={v.placeId}>
<TargetTxt platform={tablet}>{v.name}</TargetTxt>
</TargetCon>
</>
);
})}
</SeCotainer>
);
};
export default TargetFarm;