I would like to change style of checked thumb, but i cant figure how. I tried every variation.
When thumb is checked, it should change size to width: 20, height: 20 and color: white..
Can someone provide working example or change my code? Thanks!
const StyledSwitch = styled((props: SwitchProps) => (
<Switch focusVisibleClassName=".Mui-focusVisible" disableRipple {...props} />
))(({}) => ({
width: 42,
height: 26,
padding: 0,
marginRight: -16,
'& .MuiSwitch-switchBase': {
padding: 3,
margin: 2,
transitionDuration: '300ms',
'& .MuiSwitch-thumb': {
boxSizing: 'border-box',
width: 16,
height: 16,
boxShadow: 'none',
backgroundColor: 'red',
},
'&.Mui-checked': {
transform: 'translateX(16px)',
color: '#fff',
'& + .MuiSwitch-track': {
backgroundColor: '#00519E',
opacity: 1,
border: '2px solid #00519E',
},
'&.Mui-disabled + .MuiSwitch-track': {
opacity: 0.5,
},
},
'&.Mui-disabled + .MuiSwitch-track': {
opacity: 0.7,
},
},
'& .MuiSwitch-track': {
borderRadius: 26 / 2,
backgroundColor: '#FFF',
border: '2px solid #00519E',
opacity: 1,
},
}));
interface FormSwitchProps extends SwitchProps {
name?: string;
}
const FormSwitch: React.FC<FormSwitchProps> = ({ name, ...props }) => (
<FormControlLabel
control={<StyledSwitch name={name} {...props} />}
label={<span className="ml-1">{name}</span> || ''}
/>
);
export default FormSwitch;
>Solution :
To change the thumb size to width: 20, height: 20
and the color to white
when checked, you should target the checked state of the thumb. Here’s the revised styling:
const StyledSwitch = styled((props: SwitchProps) => (
<Switch focusVisibleClassName=".Mui-focusVisible" disableRipple {...props} />
))(({}) => ({
width: 42,
height: 26,
padding: 0,
marginRight: -16,
'& .MuiSwitch-switchBase': {
padding: 3,
margin: 2,
transitionDuration: '300ms',
'& .MuiSwitch-thumb': {
boxSizing: 'border-box',
width: 16,
height: 16,
boxShadow: 'none',
backgroundColor: 'red',
},
'&.Mui-checked': {
transform: 'translateX(16px)',
color: '#fff',
'& .MuiSwitch-thumb': { // Target the thumb when it's in a checked state
width: 20, // Set the width to 20
height: 20, // Set the height to 20
backgroundColor: 'white', // Set the color to white
},
'& + .MuiSwitch-track': {
backgroundColor: '#00519E',
opacity: 1,
border: '2px solid #00519E',
},
'&.Mui-disabled + .MuiSwitch-track': {
opacity: 0.5,
},
},
'&.Mui-disabled + .MuiSwitch-track': {
opacity: 0.7,
},
},
'& .MuiSwitch-track': {
borderRadius: 26 / 2,
backgroundColor: '#FFF',
border: '2px solid #00519E',
opacity: 1,
},
}));
interface FormSwitchProps extends SwitchProps {
name?: string;
}
const FormSwitch: React.FC<FormSwitchProps> = ({ name, ...props }) => (
<FormControlLabel
control={<StyledSwitch name={name} {...props} />}
label={<span className="ml-1">{name}</span> || ''}
/>
);
export default FormSwitch;
The key here is to nest & .MuiSwitch-thumb
inside the &.Mui-checked
selector to properly target the thumb when the switch is checked.