How to Override the Style of the Material-Ui Switch Component When Checked

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

Switch defaults to using the secondary color.

The color of the thumb is then controlled within the colorSecondary CSS. Here are the default styles for that class:

  /* Styles applied to the internal SwitchBase component's root element if `color="secondary"`. */
colorSecondary: {
'&$checked': {
color: theme.palette.secondary.main,
'&:hover': {
backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
'@media (hover: none)': {
backgroundColor: 'transparent',
},
},
},
'&$disabled': {
color: theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[800],
},
'&$checked + $track': {
backgroundColor: theme.palette.secondary.main,
},
'&$disabled + $track': {
backgroundColor:
theme.palette.type === 'light' ? theme.palette.common.black : theme.palette.common.white,
},
},

You can adjust the checked color in your theme with the following (which shows overriding both the thumb and the track):

  const theme = createMuiTheme({
overrides: {
MuiSwitch: {
switchBase: {
// Controls default (unchecked) color for the thumb
color: "#ccc"
},
colorSecondary: {
"&$checked": {
// Controls checked color for the thumb
color: "#f2ff00"
}
},
track: {
// Controls default (unchecked) color for the track
opacity: 0.2,
backgroundColor: "#fff",
"$checked$checked + &": {
// Controls checked color for the track
opacity: 0.7,
backgroundColor: "#fff"
}
}
}
}
});

Edit customize Switch via theme



For MUI v5

For v5, the structure of the object passed to createTheme changed. Another change is that primary is now the default color rather than secondary, so the colorPrimary styles need to be overridden instead of colorSecondary.

Here is the equivalent code for v5:

import React from "react";
import FormGroup from "@mui/material/FormGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import Switch from "@mui/material/Switch";
import { createTheme, ThemeProvider } from "@mui/material/styles";

export default function CustomizedSwitches() {
const [state, setState] = React.useState({
checkedA: true
});

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setState({ ...state, [event.target.name]: event.target.checked });
};

const theme = createTheme({
components: {
MuiSwitch: {
styleOverrides: {
switchBase: {
// Controls default (unchecked) color for the thumb
color: "#ccc"
},
colorPrimary: {
"&.Mui-checked": {
// Controls checked color for the thumb
color: "#f2ff00"
}
},
track: {
// Controls default (unchecked) color for the track
opacity: 0.2,
backgroundColor: "#fff",
".Mui-checked.Mui-checked + &": {
// Controls checked color for the track
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>
);
}

Edit customize Switch via theme

Customize material UI Switch when checked and disabled

Thanks Ryan and Giovanni. Both of your answers contributed to my figuring it out. Key thing from Ryan is that in order to use "&$disabled" in a rule, we need to have "disabled:{}" in there too. And then Giovanni's answer got me thinking about how the disabled states and checked states interact. Here was my code that got disabled to work and was able to style something that was both checked and disabled which was my ultimate goal:

const MySwitch = withStyles({
switchBase: {
// thumb when unchecked
color: "orange",
opacity: 0.8,
"&$checked": {
// thumb when checked
color: "orange",
opacity: 1,
// track when checked
"& + $track": {
backgroundColor: "black",
opacity: 1,
},
// The rules above override the default rules for graying
// out the thumb and track when the switch is disabled,
// so we have to add that back in ourselves
"&$disabled": {
// gray out the thumb
color: "#bbb",
"& + $track": {
// gray out the track
backgroundColor: "#ddd"
}
}
},
},
checked: {},
track: {},
disabled: {}
})(Switch);

How to overload material Switch component css

Below is an example showing how to customize the track color for a Switch. This is based on the approach used for the default styles.

import React from "react";
import Switch from "@material-ui/core/Switch";
import { withStyles } from "@material-ui/core/styles";

const CustomSwitch = withStyles({
colorSecondary: {
"&.Mui-checked + .MuiSwitch-track": {
backgroundColor: "purple"
}
},
track: {
backgroundColor: "blue"
}
})(Switch);

export default function Switches() {
const [state, setState] = React.useState({
checkedA: true,
checkedB: true
});

const handleChange = name => event => {
setState({ ...state, [name]: event.target.checked });
};

return (
<div>
<Switch
checked={state.checkedA}
onChange={handleChange("checkedA")}
value="checkedA"
inputProps={{ "aria-label": "secondary checkbox" }}
/>
<CustomSwitch
checked={state.checkedA}
onChange={handleChange("checkedA")}
value="checkedA"
inputProps={{ "aria-label": "secondary checkbox" }}
/>
</div>
);
}

Edit Custom Switch

How to only give MUI Switch border style when it is checked?

Remove the border from the parent (SwitchBase) and put it in the track component inside so it can be targeted by CSS selector when the state of the sibling element changes:

root: {
...
// border: '1px solid #606060', // <-------------------- comment this line
},
track: {
backgroundColor: 'transparent',
borderRadius: '10px',
border: '1px solid #606060',
height: 'auto',
opacity: 1,
},
switchBase: {
color: '#606060',
'&.Mui-checked + $track': {
border: 'none',
},
},

Codesandbox Demo

Since you're using v5, you shouldn't use withStyles anymore, it is deprecated and will be removed in v6. Here is the equivalent demo in v5 using styled instead.

Codesandbox Demo

How to override Material-UI Switch button styling

MuiSwitch: {
disabled: {
'& .MuiSwitch-thumb': {
boxShadow: 'unset'
}
}
},

Edit ecstatic-rain-xtd9k

props-dependent Switch color in Material-UI

Follow this example for passing props if you must use withStyles HOC: https://material-ui.com/styles/basics/#adapting-the-higher-order-component-api

const ColoredSwitch = withStyles({
switchBase: {
"&.Mui-checked": {
color: (props) => props.customchecked
}
},
checked: {},
track: {}
})((props) => {
const { classes, ...other } = props;
return <Switch classes={{ switchBase: classes.switchBase }} {...other} />;
});

Edit Material demo (forked)


You can also use makeStyles

const useStyles = makeStyles({
switchBaseChecked: {
"&.Mui-checked": {
color: (props) => props.color
}
}
});

export default function Switches() {
const props = { color: "green" };
const classes = useStyles(props);
return (
<Switch
color="primary"
classes={{
checked: classes.switchBaseChecked
}}
/>
);
}

Edit Material demo (forked)

I want to change material ui swith color

Do you want results like that?

Codesandbox: https://codesandbox.io/s/priceless-bouman-19xup?file=/src/App.js

Can you overwrite styles in Material UI using css/scss?

Below is the correct syntax:

.button {
padding: 10px;
margin-bottom: 10px;
&:global(.MuiButton-containedPrimary) {
border: 2px solid red;
background-color: red;
}
}

Edit SCSS modules

The example above has two key changes:

  1. Using :global(.MuiButton-containedPrimary). Without using :global, CSS modules will transform the MuiButton-containedPrimary into a class name unique to this module and then it won't match what Material-UI puts on the button.

  2. Adding the & in front effectively creates a selector like .button.MuiButton-containedPrimary matching an element with both classes on it. Your original syntax would treat .MuiButton-containedPrimary as a descendant selector and only match elements with that class that are a descendant of the button rather than the button itself.



Related Topics



Leave a reply



Submit