Mui dark mode switch12/16/2023 This is the final (and simplest) step before you'll have a functioning dark mode toggle. If you've made it this far, pat yourself on the back. import = DarkModeContextĬonst theme = localStorage.getItem("preferred-theme")Ĭonst themePreference = localStorage.getItem("preferred-theme") We do it by nesting our themes: we define our global styles for both light and dark modes, and then spread that across our styles for our separate light and dark themes. Unlike other tutorials, we only use one theme, yet we provide multiple styles. One of the reasons why I think this approach is the best is because it has a single source of truth. If you're a visual learner, I hope that diagram gives you a mental picture of where we're headed. Light theme, containing styles to be applied when the light mode is active. Dark theme, styles applied when dark mode is active, and lastly, ourģ. Base theme, styles to be applied globally across both light and dark modes.Ģ. This dispatches a function via our reducer to change the theme and sets the local storage to the user's newly-preferred theme.ġ. It contains the button to toggle the dark/light theme and does so with an onClick function. Index does the least amount of work but the most important. We'll wrap our application with our Theme using the Material-UI ThemeProvider. If not, we'll set it to the default of our choosing. Layout is where we'll initially check the user's local storage to see if they have a previously set theme. It prevents flashes of unstyled content with server-side rendering. ![]() Gatsby-ssr serves the same purpose: wrapping our application with our Context Provider to make it accessible everywhere in our app. ![]() It allows our Gatsby site to have dynamic state. Gatsby-browser wraps our application with our Context Provider. It'll contain our useContext and useReducer functions. ThemeHandler will.well, handle whether to display a light or dark theme. You'll notice it looks similar to a typical Gatsby.js project with the exception of the ThemeHandler.js file. and here's how the final product will look and behave:īefore we dive into the code, let's first look at the project structure (which is available on CodeSandbox).
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |