skip to Main Content

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"}
/>

The problem is the color is applied only when the condition is true and the switch is checked , while if it’s unchecked it will be the default gray color stylings

I’ll appreciate any help.

I was trying to change the color of MUI switch component but the unchecked state remain always on default gray color

2

Answers


  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>
      );
    }
    
    Login or Signup to reply.
  2. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search