I want to setup a dark and light theme for my react app. I have my Sidebar.js, Header.js and Footer.js files in my Components folder which is within the src folder.
My app loads light theme on default and the toggle switch is in the sidebar. If the I try to switch to dark theme, just the sidebar and the body switches, the header and footer remain in light theme.
Sidebar.js
//Sidebar.js
const Sidebar = () => {
const [theme, setTheme] = useState(lightTheme);
const toggleTheme = () => {
setTheme(prevTheme => (prevTheme === darkTheme ? lightTheme : darkTheme));
};
return (
<SubMenuItem as="div" onClick={toggleTheme}>
{theme === darkTheme ? 'Light Theme' : 'Dark Theme'}
</SubMenuItem>
How do i get my header and footer to get the state of the toogleTheme?
2
Answers
Well, you can create Context using Context API (which is dedicated in React) and create a ThemeContext and a ThemeContextProvider, then wrap your components with it and pass that state wherever you want.
You can follow this link’s description to get the idea of what you need to do:
Some methods of doing this task…
Theming often works where you have a base css file that defines your dark and light rules, and then you have a function that can toggle the class on the
html
element so that every element on the page is affected.One method to solve with React is to use a custom hook that describes the theme state and provides a theme setter, and then updates the
html
class name to match the change in that state when one of the radio buttons is clicked.