Search code examples
javascriptreactjsmaterial-uiuiswitch

props-dependent Switch color in Material-UI


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)

Blue 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)

Default switch

I guess I must be doing something wrong but can't figure out what.


Solution

  • 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)