For React Versions Supporting Hooks (> 16.8)
(see stackblitz provided in the question)
To update the internal state of a React (Material Design) component, you must utilize the useState()
method. By creating a state property named value
and setting it to male
, you inform the MD RadioGroup component about which radio button should be the default selection. Subsequently, the value
property is employed as the value attribute within the radio group to establish the default choice.
A small modification is required on line 24 of the referenced sandbox:
Replace:
const [value, setValue] = React.useState("female");
With:
const [value, setValue] = React.useState("male");
For React Versions without Hooks (< 16.8)
If your project doesn't support hooks, you'll need to transform your function into a React Component Class that utilizes a standard state variable approach. However, an additional concern arises when using Material Design since it calls a React method not present in earlier versions of React (createContext()
). It's recommended to downgrade Material Design to v1.0.0 if you're working with React versions prior to 16.8.
Here is the relevant code snippet:
class RadioButtonsGroup extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.classes = {
root: { display: "flex" },
formControl: { margin: 13 },
group: { margin: 10 },
};
this.state = { value: "male" };
}
handleChange(event) {
this.setState({ value: event.target.value });
}
render() {
return (
<div className={this.classes.root}>
<FormControl component="fieldset" className={this.classes.formControl}>
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup
aria-label="Gender"
name="gender1"
className={this.classes.group}
value={this.state.value}
onChange={this.handleChange}
>
<FormControlLabel
value="female"
control={<Radio />}
label="Female"
/>
<FormControlLabel value="male" control={<Radio />} label="Male" />
<FormControlLabel value="other" control={<Radio />} label="Other" />
<FormControlLabel
value="disabled"
disabled
control={<Radio />}
label="(Disabled option)"
/>
</RadioGroup>
</FormControl>
<FormControl component="fieldset" className={this.classes.formControl}>
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup
aria-label="gender"
name="gender2"
className={this.classes.group}
value={this.state.value}
onChange={this.handleChange}
>
<FormControlLabel
value="female"
control={<Radio color="primary" />}
label="Female"
labelPlacement="start"
/>
<FormControlLabel
value="male"
control={<Radio color="primary" />}
label="Male"
labelPlacement="start"
/>
<FormControlLabel
value="other"
control={<Radio color="primary" />}
label="Other"
labelPlacement="start"
/>
<FormControlLabel
value="disabled"
disabled
control={<Radio />}
label="(Disabled option)"
labelPlacement="start"
/>
</RadioGroup>
<FormHelperText>labelPlacement start</FormHelperText>
</FormControl>
</div>
);
}
}