Home > other >  How to change the color of thumb switch react js
How to change the color of thumb switch react js

Time:09-27

I have a switch that I would like to change the color of the circle to a dark gray. I've looked on the internet but I can't quite understand how to use the css rules that exist in the component documentation. Can anybody help me!? Here is my code:

const ThemeToggle = () => {

    const { theme, setTheme } = useContext(ThemeContext);
    const handleThemeToggle = () => {
        setTheme(theme === 'light' ? 'dark' : 'light');

        if (theme === 'light') {
            document.body.classList.add('darkBackground');
        } else {
            document.body.classList.remove('darkBackground');
        }
    };



    return <div>
        <Switch
            uncheckedIcon={false}
            checkedIcon={false}
            onColor={'#eee'}
            onChange={handleThemeToggle}
            checked={theme === 'light'}

        />
    </div>
}

export default ThemeToggle;

Component Documentation: https://mui.com/material-ui/api/switch/

I use this switch to change the mode. So while in light mode the thumb would be grayed out. In dark mode, the thumbnail would be white

**ThemeContext:

export const ThemeContext = React.createContext({} as IThemeContext);

const App: React.FC = () => {
  const storedTheme = localStorage.getItem("darkTheme");
  const [theme, setTheme] = useState(storedTheme);


  useEffect(() => {
    localStorage.setItem("darkTheme", theme);
  })

  return (

    <ThemeContext.Provider value={{ theme, setTheme }}>
      <CssBaseline />
      <BrowserRouter>
        <GlobalStyle />
        <AppRouter />
      </BrowserRouter>

    </ThemeContext.Provider>
  );
};

CodePudding user response:

Try to overwrite this class:

.MuiSwitch-colorSecondary.Mui-checked {
  color: green; // any color you want
}

Example: https://codesandbox.io/s/material-ui-switch-forked-2plbik?file=/src/components/SwitchContainer.jsx

CodePudding user response:

I created the following codesandbox where you can see how I change the colour of the Switch component with CSS global class this website: https://mui.com/material-ui/api/switch/#css provides your case that you just want it when its darkBackground:

.darkBackground .MuiSwitch-switchBase.Mui-checked {
  color: white;
}

.darkBackground .MuiSwitch-switchBase.Mui-checked   .MuiSwitch-track {
  background-color: white;
}

I wasn't able to change the context that's why i asked you if you could share it but if you make the context work in this demo it should work as you expect:

DEMO:

https://codesandbox.io/s/adoring-carson-jxlp58?file=/src/styles.css

  • Related