简体   繁体   中英

MUI theme light/dark switch in header(AppBar)

I'm trying to find a way to switch between dark and light theme in my web app. I want to add the switch in my AppBar component which is inside my header but I'm not sure how to get it to work on all of the web app and not just the header.

AppBar.js :

//imports ... 

const AppBar = () =>{

 const [theme, setTheme] = useState(false);

 const changeTheme = () => {
    setTheme(!theme);
 };
 //rest of the code....

 <Box sx={{ flexGrow: 0 }}>
   <Switch checked={theme} onChange={changeTheme} />
 </Box>
};
export default AppBar;

here is the code from the Header.js

const Header = () => {
  return (
    <header>
      <AppBar />
    </header>
  );
};

export default Header;

so the header is just rendering one component one could get rid of it if it was necessary.

and here is my App.js (routes)

//imports ...

//themes ...

const app = ()=>{
 return (
    <React.Fragment>
      <ThemeProvider theme={theme ? lightTheme : darkTheme}>
        <CssBaseline />
        <Router>
          <Header />
          <Routes>
           //Routes ...
          </Routes>
          <Footer />
        </Router>
      </ThemeProvider>
    </React.Fragment>
  );
}

export default App;

I'd really appreciate the help and Thanks in advance!

you can store the value of theme inside context or redux store and change it using a dispatch function once that value changes the whole component related to it will re render !, so your component will change the value inside context ! rather than having the value stuck inside one component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM