Reputation: 1728
I have an issue working with the material UI RadioGroup in combination with FormControlLabels returned by a component.
Currently I try this:
<FormControl component="fieldset">
<RadioGroup
row
name="genreSelection"
className="genre-wrapper"
value={this.state.selection}
onChange={this.handleRadioSelection}
>
{
this.state.genres.map(genre => (
<GenreItem key={genre} label={genre} radioButton/>
))
}
</RadioGroup>
</FormControl>
And the render function of GenreItem looks like this:
if (this.props.radioButton) {
return (
<FormControlLabel
value={this.props.label}
label={this.props.label}
control={
<Radio/>
}
className="genre-item"
/>
);
}
// Another return here
My problem is that the FormControlLabel isn't working correctly as "handleRadioSelection" isn't triggered on any selection.
By now I found out that the input element generated from the Radio element doesn't have name="genreSelection" as attribute which means it doesn't belong to the RadioGroup defined above.
If I put the FormControlLabel out of GenreItem and directly into the this.state.genres.map function everything is working just fine.
Am I doing something wrong or is this just a limitation of material UI?
Upvotes: 0
Views: 10650
Reputation: 81136
If you look at the code of RadioGroup you'll find that it clones the children that you provide to it and adds several properties. You need to carry those properties down into FormControlLabel
.
You can accomplish that by changing GenreItem
to render the FormControlLabel
as follows:
// assign radioButton separately so it isn't part of labelProps
const { radioButton, ...labelProps } = this.props;
if (radioButton) {
<FormControlLabel {...labelProps }
label={this.props.value}
control={
<Radio/>
}
className="genre-item"
/>
Adding {...labelProps}
will carry forward the props added by RadioGroup.
Also if you want the label and value to be the same, it is important to pass value
explicitly to GenreItem
rather than label
since RadioGroup
uses the value
prop to help determine the checked
property.
Here's a working example:
Upvotes: 4