I have a dynamic array that consists of many objects. For example, the array is,
const dynamicArray=[{type:A, value:[1,2,3]}, {type:B, value:[4,5,6]}]
There might be so many objects. I mapped this array and returned radio buttons so that I can pick options. What I did is,
{
dynamicArray.map(item=>(
<>
<h1>{item.type}</h1>
<RadiaGroup>
{item.value.map(value => (
<Radio>{value}</Radio>))
}
</RadioGroup>
</>
)
}
I want to get the value onSelect to the radio button, and also want to get other selected radio buttons value. like, if user clicks on type A, i want to have it's value and also the other object Type B's value. Like, 1 from A, and 4 from B
CodePudding user response:
So, you need to onChange
event on the RadioGroup
, and you need to pass the item.type
as a parameter.
const dynamicArray=[{type:A, value:[1,2,3]}, {type:B, value:[4,5,6]}]
const [value, setValue] = useState(dynamicArray.map(i => ({type: i.type, value: '' })))
const handleChange = (event: React.ChangeEvent<HTMLInputElement>, index: number) => {
setValue(prev => {
prev[index].value = event.target.value
return [...prev]
})
};
{
dynamicArray.map((item, index) =>(
<>
<h1>{item.type}</h1>
<RadiaGroup onChange={(e) => handleChange(e, index)} value={value[index].value}>
{item.value.map(value => (
<Radio>{value}</Radio>))
}
</RadioGroup>
</>
)
}