I am using 2 arrays and rendering it as parent and child map function
Array :
const array1 = [{id: 1,message: "apple",},{id: 2,message: "banana",},{id: 3,message: "cherry",},];
const array2 = [{id: 4,reply: "mango",},{id: 5,reply: "grape",},{id: 6,reply: "kiwi",},];
Now when I render these arrays as parent and child and in onChange function in radio button i get each time "1" as id and I want parent’s id 2 and 3 also on onChange function.
export const app = () => {
const array1 = [{id: 1,message: "apple",},{id: 2,message: "banana",},{id: 3,message: "cherry",},];
const array2 = [{id: 4,reply: "mango",},{id: 5,reply: "grape",},{id: 6,reply: "kiwi",},];
const handleChange = (parentId) => {
console.log(parentId) // Each time returns 1 and not 2 and 3
}
return (
<div>
{array1.map((parentItem) => {
return (
<div key={parentItem.id}>
<span>{parentItem.message}</span>
{array2.map((childItem) => {
return (
<div key={childItem.id}>
<input
type="radio"
id={childItem.id}
value={childItem.reply}
onClick={()=>handleChange(parentItem.id)}
/>
<label htmlFor={childItem.id}>{childItem.reply}</label>
</div>
);
})}
</div>
);
})}
</div>
);
};
>Solution :
The issue is that you have given multiple input elements the same id
and each label is linked to the first element of that id in the document. Therefore, clicking on any label will result in checking one of the radio buttons in the first <div>
(where parentItem.id
is 1
).
To rectify this, ensure that your ids are unique across the document.
const id = parentItem.id + '_' + childItem.id;
return (
<div key={childItem.id}>
<input
type="radio"
id={id}
value={childItem.reply}
onClick={() => handleChange(parentItem.id)}
/>
<label htmlFor={id}>{childItem.reply}</label>
</div>
);