Home > Software engineering >  Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled
Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled

Time:09-21

I'm receiving this error in the browser console when I use a Switch component.

...
import { Button, Form, FormText, Label, Input } from 'reactstrap';
import { FormGroup, Switch, Radio, FormControlLabel, RadioGroup  } from '@material-ui/core';
...

// state variable to keep my Switch values. I grab the values from the database
const [ companySettings, setCompanySettings ] = useState({});

...

// Where I render the Switches
<Form inline>
    <div className="row">
        <div className="col-sm-12">
            <FormGroup row>
                <Switch name="escrow" checked={companySettings.payCCFee} onChange={() => setCompanySettings({...companySettings, payCCFee: !companySettings.payCCFee})} aria-label="Company Pay CC Fee" />
                <Label for="escrow" className="mr-sm-10">
                    Company pays credit card convenience fee? 
                </Label>
            </FormGroup>
        </div>
    </div>
</Form>

When I click on the Switch, the browser console shows:

Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.
Elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled SwitchBase element for the lifetime of the component.
The nature of the state is determined during the first render, it's considered controlled if the value is not `undefined`.

CodePudding user response:

The problem is due to the state object companySettings being initialized as an empty object. Doing this in the checked={companySettings.payCCFee} in the switch component returns undefined and the react thinks this is a uncontrolled component, since no value is provided. You can either initialize the state object to have some default value like below

const [ companySettings, setCompanySettings ] = useState({payCCFee: false}); // or true based on the UX

The second option is you initialized the empty state, but use a double negation operator to convert the undefined to false.

checked={!!companySettings.payCCFee}
  • Related