How to change color of Switch component in material ui

Viewed 22

I wanted to change color of switch component when is inactive to red, and active to green but can't change to red in inactive. Still have default value.

switch image

1 Answers

I have tried with this example:

import * as React from 'react';
import Switch from '@mui/material/Switch';

export default function ControlledSwitches() {
  const [checked, setChecked] = React.useState(true);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setChecked(event.target.checked);
  };

  return (
    <Switch
      sx={{
        '& .MuiSwitch-switchBase': {
          '&.Mui-checked': {
            color: 'green',
            '& + .MuiSwitch-track': {
              background: 'green',
            },
          },
          '&.Mui-disabled.MuiSwitch-thumb': {
            color: 'red',
          },
        },
        '& .MuiSwitch-thumb': {
          color: !checked && 'red',
        },
        '& .MuiSwitch-track': {
          backgroundColor: 'red',
        },
      }}
      checked={checked}
      onChange={handleChange}
      inputProps={{ 'aria-label': 'controlled' }}
    />
  );
}

I have followed this documentation examples:

https://mui.com/material-ui/react-switch/#customization

Related