ingielek
ingielek

Reputation: 41

Material-ui FormControlLabel not checked on default

I have a problem with my formcontrollabel. I want the radio button to be checked on default, but property checked doesn't seem to work.

I have tried with logical statements, simply giving true as an argument, but nothing seems to work. Any thoughts?

Here's my code :

const styles = theme => ({
    root: {
        display: 'flex',
    },
    formControl: {
        margin: theme.spacing.unit * 3,
    },
    group: {
        margin: `${theme.spacing.unit}px 0`,
    },
});

class SelectPeriod extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedValue: 'daily'
        };
    }

    handleChange = (value) => {
        this.setState({selectedValue: value});
    };

    render() {
        const { classes} = this.props;
        return (
            <div>
                <FormControl component="fieldset" className={classes.formControl}>
                    <FormLabel component="legend">Time Period</FormLabel>
                    <RadioGroup
                        aria-label="TimePeriod"
                        name="timePeriod"
                        className={classes.group}
                        value={this.state.value}
                        onChange={this.handleChange}
                    >
                        <FormControlLabel value="daily" checked control={<Radio color="primary" />} label="Daily" />
                        <FormControlLabel value="weekly" control={<Radio color="primary" />} label="Weekly" />
                        <FormControlLabel value="monthly" control={<Radio color="primary" />} label="Monthly" />
                    </RadioGroup>
                </FormControl>
            </div>
        )
    }
}
SelectPeriod.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(SelectPeriod);

Upvotes: 2

Views: 7930

Answers (1)

grenzbotin
grenzbotin

Reputation: 2565

  1. In your <RadioGroup> you pass the wrong state (you defined selectedValue, not value)
<RadioGroup
  aria-label="TimePeriod"
  name="timePeriod"
  className={classes.group}
  value={this.state.selectedValue}
  onChange={this.handleChange}
>

(With the value props in RadioGroup you will control which radio field will be selected.)

  1. I guess you will have a problem with your handleChange function. Just check material ui documentation again. https://material-ui.com/demos/selection-controls/

Upvotes: 3

Related Questions