Reputation: 2183
The following code, adapted from Material-UI docs for customizing Switch
allows to set the switch color to blue:
import React from 'react'
import Switch from '@material-ui/core/Switch'
import {withStyles} from '@material-ui/core/styles'
const ColoredSwitch = withStyles({
switchBase: {
'&$checked': {
color: 'blue',
},
},
checked: {},
track: {},
})(Switch)
But when trying to adapt it so that the color can be set by component properties, it just doesn't work. Event the following code (which is only pseudo-dynamic) renders to a default switch:
const ColoredSwitch = withStyles({
switchBase: {
'&$checked': {
color: props => 'blue',
},
},
checked: {},
track: {},
})(Switch)
I guess I must be doing something wrong but can't figure out what.
Upvotes: 0
Views: 1117
Reputation: 14201
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} />;
});
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
}}
/>
);
}
Upvotes: 1