Tanmoy Basak
Tanmoy Basak

Reputation: 142

Material UI checkbox complaining to be uncontrolled

I'm using Material UI kit for React. I'm making Checkboxes dynamically from states and updating them,

But I'm getting uncontrolled element error.

this.state = {
    services : [{service: "s1", value: false},
                {service: "s2", value: false},
                {service: "s3", value: false},
               ]
};

handleServiceCheck = (i) => {
    let services = this.state.services;
    services[i].value = !services[i].value;
    this.setState({ services: services });
};

this.state.services.map((service, i) => (
    <FormControlLabel key={i}
        control={
            <Checkbox
                checked={service.value}
                onChange={() => this.handleServiceCheck(i)}
                value={service.service}
                className={classes.checkBox}
            />
        }
        label={service.service}
    />
))

Uncontrolled Input Element

Upvotes: 1

Views: 2382

Answers (2)

Srikanth Reddy
Srikanth Reddy

Reputation: 1

checked={service.value || false}

or

checked={Boolean(service.value)}

Upvotes: 0

Andrei
Andrei

Reputation: 1873

There are several problems here.

First of all, the checked prop of Checkbox needs a boolean, but you're passing integers.

Second of all, when mutating a previous state, you shouldn't mutate it in place, you should pass a function to setState that takes the previous state and returns the new one.

handleServiceCheck = (i) => {
  this.setState(prevState => ({services: 
    prevState.services.map((s, idx) => {
      return i === idx
        ? { ...s, value: !s.value }
        : s
    })
  }));
};

Here's a CodeSandbox sample I created with the full fixed working version.

Upvotes: 2

Related Questions