React warning MUI: A component is changing the default checked state of an uncontrolled SwitchBase after being initialized

Viewed 4982

I'm trying to render a mui Switch component with default checked value. But it isn't working and i'm getting the warning.

MUI: A component is changing the default checked state of an uncontrolled SwitchBase after being initialized. To suppress this warning opt to use a controlled SwitchBase. 3 useControlled.js:27

I have also tried setting checked property along with onChange but still it doesn't work! I can't figure out what i'm doing wrong here.

{details.schedule.days.map((d) => (
                <StyledTableRow>
                  <TableCell>
                    <Typography variant="subtitle1" fontWeight="bold">
                      {d.day}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <FormControlLabel
                      control={
                        <Switch
                          onChange={(e, checked) => {
                            setDetails((p) => {
                              let prev = { ...p };
                              prev.schedule?.days?.find(
                                (el) =>
                                  el.day === d.day &&
                                  (d.open = e.target.checked)
                              );
                              return prev;
                            });
                          }}

                          defaultChecked={d.open}
                        />
                      }
                      labelPlacement="bottom"
                      label={d?.open ? `Open` : `Closed`}
                    />
                  </TableCell>
                </StyledTableRow>
              ))}
2 Answers

use "checked" instead of "defaultChecked" will address this waring

I was also getting the same error when using the defaultChecked property on a controlled switch.

As mentioned in the comments you should use the checked property.

In the docs it says in regard to the defaultChecked property:

Use when the component is not controlled

https://mui.com/api/switch/#props

Related