Reputation: 1
I'm using switch component from MUI, I want to toggle the styling between two colors
<Switch
color={dataType === "expenses" ? "error" : "secondary"}
onChange={handleOnSwitch}
checked={dataType === "expenses"}
/>
i can't find what is the specific props i should pass to customize the offSwitch color, in the documentations there is only props to the checked case, i want to change the switch color while unchecked to something other than the default gray.
I'll appreciate any help.
Upvotes: 0
Views: 443
Reputation: 193
You just need to use style props like that
<FormControl required>
<FormLabel id="category-status" className={classes.inputLabel}>
Status
</FormLabel>
<FormControlLabel
control={(
<Switch
checked={formData?.Status}
onChange={handleChange}
name="Status"
inputRef={statusRef}
onKeyDown={(e) => handleFormEnterKey(e, IconURL)}
style={{ color: formData?.Status === true ? '#33cf4d' : 'gray' }}
/>
)}
/>
</FormControl>
Upvotes: 1
Reputation: 1
Here I am writing a sample code for you. You can get the look you want by changing the styled codes here.
import Switch from '@mui/material/Switch';
import { styled } from '@mui/material/styles';
import FormControlLabel from '@mui/material/FormControlLabel/FormControlLabel';
export default function BasicSwitches() {
const MaterialUISwitch = styled(Switch)(() => ({
width: 62,
height: 34,
padding: 7,
'& .MuiSwitch-switchBase': {
margin: 1,
padding: 0,
transform: 'translateX(6px)',
'&.Mui-checked': {
color: '#fff',
transform: 'translateX(22px)',
'& + .MuiSwitch-track': {
opacity: 1,
backgroundColor: 'blue',
},
},
},
'& .MuiSwitch-thumb': {
backgroundColor: 'red',
width: 32,
height: 32,
'&::before': {
content: "''",
position: 'absolute',
width: '100%',
height: '100%',
left: 0,
top: 0,
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
},
},
'& .MuiSwitch-track': {
opacity: 1,
backgroundColor: 'red',
borderRadius: 20 / 2,
},
}));
return (
<div>
<FormControlLabel
control={<MaterialUISwitch sx={{ m: 1 }} defaultChecked />}
label="MUI switch"
/>
</div>
);
}
Upvotes: 0