Reputation: 879
I have an input form switch in Material UI and I'd like the track and button to be red when on, exactly like in this example. All the switch styling examples on Material UI's website use withStyles, but I'm unsure why I can't use useStyles instead? Is it possible to do it with useStyles?
Here is my attempt which is not working!
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Switch from '@material-ui/core/Switch';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
const useStyles = makeStyles(theme => ({
switchBase: {
'&$checked + $track': {
backgroundColor: 'red',
},
},
}));
export default function SwitchesSize() {
const classes = useStyles()
const [checked, setChecked] = React.useState(false);
const toggleChecked = () => {
setChecked((prev) => !prev);
};
return (
<FormGroup>
<FormControlLabel
control={<Switch size="small" checked={checked} onChange={toggleChecked} />}
label="Small"
classes={{ switchBase: classes.switchBase }}
/>
</FormGroup>
);
}
Many thanks for your help :)
Katie
Upvotes: 0
Views: 1437
Reputation: 3772
To style the Switch
with useStyles
root component needs to be targeted.
<FormGroup>
<FormControlLabel
control={
<Switch
color="default"
classes={{
track: classes.switchTrack,
switchBase: classes.switchBase,
}}
size="small"
checked={checked}
onChange={toggleChecked}
/>
}
label="Small"
// classes={{ switchBase: classes.switchBase }}
/>
</FormGroup>
useStyles object:-
const useStyles = makeStyles((theme) => ({
switchTrack: {
backgroundColor: "#000"
},
switchBase: {
color: "#000",
"&.Mui-checked": {
color: "green"
},
"&.Mui-checked + .MuiSwitch-track": {
backgroundColor: "green"
}
},
}));
working sandbox link:- https://codesandbox.io/s/prod-wave-e9otk
Upvotes: 2