I am seeking to customize the color of the switch component based on its checked and unchecked state. By default, it displays in red. My goal is to have the "ball knob" appear yellow when the switch is checked and grey when it is not. This styling must be implemented using createMuiTheme
and ThemeProvider
as I cannot apply classes directly to the component in this particular project.
I have attempted to replicate the customization of the purple knob example provided by Material-UI here: https://codesandbox.io/s/x8bz8 Source: https://material-ui.com/components/switches/
Despite managing to set the colors for the track in both states, as well as the color of the ball when unchecked, I have hit a roadblock with changing the color of the ball when it is checked (it reverts back to red). Can anyone offer assistance in applying the desired color style to the ball when checked?
I have created a CodeSandbox where I have been experimenting: https://codesandbox.io/s/material-demo-b6153
const theme = createMuiTheme({
overrides: {
MuiSwitch: {
switchBase: {
color: "#ccc", // this works
"&$checked": { // this doesn't work
color: "#f2ff00"
}
},
track: { // this works
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 also attempted:
checked: {
"& + $bar": {
opacity: 1.0,
backgroundColor: "rgb(129, 171, 134)" // Light green, aka #74d77f
}
},
This was suggested in response to a similar question found here: How do I properly use theme overrides for the MUISwitch "bar" color when checked? However, it does not seem to be working, possibly due to version differences or discrepancies in styles when used within createMuiTheme
.