how to apply dark mode in react

Viewed 33

I have an application where I would like to apply dark mode to both my UI components and components that were created by the team. I managed to get the dark theme applied to material UI components but I can't think of a way to combine the logic used for the material ui and the logic of the other components. Can anyone give me a hint?

My app:


const App: React.FC = () => {

  
  const [darkMode, setDarkMode] = useState(false)
  const theme = createTheme({
    palette: {
      mode: darkMode ? 'dark' : 'light'
    },
  })



  return (
    <ThemeProvider theme={theme}>

      <IconButton id="dark-mode" onClick={() => { setDarkMode(!darkMode) }}>{theme.palette.mode === 'dark' ? <Brightness7 /> : <Brightness4 />}</IconButton>
      <BrowserRouter>
        <GlobalStyle />
        <AppRouter />

      </BrowserRouter>
    </ThemeProvider>
  );
};

export default App;

In the app was where I put the logic to handle the change of dark mode in material ui components. The application has different modules. Around 7, and they all use both material ui components and created components. I didn't create these components, so I don't know the best way to customize them in dark mode.

Here's how I'm trying to do dark mode on the other components:


  const [changeTheme, setChangeTheme] = useState("light");

  const toggleTheme = () => {
    if (changeTheme === 'light') {
      window.localStorage.setItem("changeTheme", "dark");
      setChangeTheme("dark");
    } else {
      window.localStorage.setItem("changeTheme", "light");
      setChangeTheme("light");
    }
  };

  useEffect(() => {
    const localTheme = window.localStorage.getItem("changeTheme");
    localTheme && setChangeTheme(localTheme);
  }, []);
<ThemeProvider theme={changeTheme === 'light' ? lightTheme : darkTheme}>
      

        <Button onClick={toggleTheme}>Change Theme</Button>
.......
</ThemeProvider>

globals file:

import { createGlobalStyle } from "styled-components";

export default createGlobalStyle`
  *,
  *::after,
  *::before {
    box-sizing: border-box;
  }
  body {
    background: ${({ theme }) => theme.body};
    color: ${({ theme }) => theme.text};
    margin: 0;
    padding: 0;
    font-family: sans-serif;
    transition: all 0.25s linear;
  }
`;

already exists in a global styles file in the application but if I try to pass the object as a value to change the color, the file says it doesn't recognize, for example, the name 'text'

0 Answers
Related