I’m using a predefined set of arrays to populate several RadioGroups. The components hierarchy is defined in the codesandbox to mimic the one in my project. Sorry if it looks verbose, there is a reason for it. Anyway, every time I hit the radio button it says to use a controlled radiogroup. According to MaterialUI, it says to add value and onChange to the Radiogroup instead of the individual Radio component. The problem is, the value is looped over the array and dynamically assigned. What am I doing wrong?
codesandbox here Thanks in advanced
<FormControl>
<RadioGroup name="row-radio-buttons-group" defaultValue={defaultValue}>
<FormLabel> {radiolabel} </FormLabel>
{radiodata.map((item) => {
return (
<div key={item} style={{ display: "flex", flexDirection: "row" }}>
<FormControlLabel
control={
<Radio
size="small"
value={item}
name={item}
checked={radiovalues[item]}
onChange={(e) => onChange(e)}
/>
}
label={item}
/>
</div>
);
})}
</RadioGroup>
</FormControl>
2
Answers
For the Radio
name
attribute, you should use the same name for each Radio component in the RadioGroup.For the Radio
checked
attribute, it should be a boolean, something likevalues.itemId == item.itemId
to compare the selected value to the value for that Radio button.You can replace the onChange with onClick event handler, to update the selected value to the clicked value.
onClick = (() => {setFieldValue('itemId', item.itemId)})
.I think what you’re looking for is basically removing the handler from the Radios in your codesandbox and just moving it to RadioGroup instead. Rather than passing the value to the Radio directly, RadioGroup does that for you. See this updated code sandbox (the only file I updated is CustomRadioGroup.js)
Hope it helps