Usama Maqsood
Usama Maqsood

Reputation: 76

Mui Switch track color is not working when checked

I want different colors of track on checked and unchecked. On unchecked the track color is working but on checked the background color is default:

Checked:

Checked

Unchecked:

Unchecked

import Switch from '@mui/material/Switch';

<Switch
  sx={{
    ".MuiSwitch-thumb": {
      backgroundColor: "#FF9528"
    },
    ".MuiSwitch-track": {
      backgroundColor: "#FF4823"
    },
    "& .Mui-checked": {
      ".MuiSwitch-thumb": {
        backgroundColor: "#FF4823"
      },
      ".MuiSwitch-track": {
        backgroundColor: "#FF4823"
      }
    }
  }}
/>

Upvotes: 0

Views: 597

Answers (1)

Taiwei Tuan
Taiwei Tuan

Reputation: 1132

You are very close.

In the example provided by MUI documentation at the Customize section, for some reason, the checked version of the track needs to have CSS selector of + so the name should be+.MuiSwitch-track instead of just .MuiSwitch-track.

UPDATED

So the default path is overwriting the checked version of the styling, therefore we need to extend the CSS selector a bit so the custom styling will have slight higher priority than the default one. Below is how I get it fixed inspired from the official doc.

  <Switch
    sx={{
      ".MuiSwitch-thumb": {
        backgroundColor: "#FF9528"
      },
      ".MuiSwitch-track": {
        backgroundColor: "#FF4823"
      },
      "& .MuiSwitch-switchBase": {
        "&.Mui-checked": {
          "+ .MuiSwitch-track": {
            backgroundColor: "#FF4823"
          },
          ".MuiSwitch-thumb": {
            backgroundColor: "#FF4823"
          }
        }
      }
    }}
  />

Link to the example code in MUI doc -- https://mui.com/material-ui/react-switch/#customization

Here is a demo in CodeSandbox with your code https://codesandbox.io/s/sad-jasper-5vqjgn?file=/src/App.tsx

Upvotes: 2

Related Questions