How can I override the style of the Material-UI switch component when checked?

I want to control the color of the switch component, both when it is checked and when is is unchecked. By default it is red. I want the "ball knob" to be yellow when the state of the switch is checked: true and I want it to be grey when is it checked: false

I must be achieving the styling with the use of createMuiTheme and ThemeProvider I cannot be using classes directly on the component due to the nature of my project.

I have tried to follow the styling example of their custom purple knob here: https://codesandbox.io/s/x8bz8
Source: https://material-ui.com/components/switches/

Unfortunately I haven’t been able to figure out how to controle the color the the ball when it is checked (it always falls back to the default red). I have succeeded setting the colors of the track when both checked and not checked, and I have also been able to set the color of the ball when it is not checked. Can someone help me figure out how I can apply color style to the ball when it is checked?

I have made a CodeSandbox where I have been messing around: https://codesandbox.io/s/material-demo-b6153

 const theme = createMuiTheme({
    overrides: {
      MuiSwitch: {
        switchBase: {
          color: "#ccc", // this is working
          "&$checked": { // this is not working
            color: "#f2ff00"
          }
        },
        track: { // this is working
          opacity: 0.2,
          backgroundColor: "#fff",
          "$checked$checked + &": {
            opacity: 0.7,
            backgroundColor: "#fff"
          }
        }
      }
    }
  });

  return (
    <ThemeProvider theme={theme}>
      <FormGroup>
        <FormControlLabel
          control={
            <Switch
              checked={state.checkedA}
              onChange={handleChange}
              name="checkedA"
            />
          }
          label="Custom color"
        />
      </FormGroup>
    </ThemeProvider>
  );

I have also tried this:

checked: {
  "& + $bar": {
    opacity: 1.0,
    backgroundColor: "rgb(129, 171, 134)" // Light green, aka #74d77f
  }
},

Which was proposed in this answer to a somewhat similar question: How do I properly use theme overrides for the MUISwitch "bar" color when checked? but that does not seem to be working for what ever reason, maybe differences in MUI version or because the styles are different when created within createMuiTheme.

53 thoughts on “How can I override the style of the Material-UI switch component when checked?”

Leave a Comment