I have this React app and I’m trying to set it up where if the main div id is set to light
, the background is a light color and if set to dark
it’s a dark color. The ThemeContext is so it affects the entire web page.
export const ThemeContext = createContext(null);
function App(props) {
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
setTheme((curr) => (curr === "light" ? "dark" : "light"));
};
return (
<div id={theme}> // this needs to change from light to dark when I click on the toggler
<ThemeContext.Provider value={{ theme, toggleTheme }}>
<Header theme={theme} toggleTheme={toggleTheme} />
<ToastContainer />
<Container className="my-2">
<Outlet />
</Container>
<Footer />
</ThemeContext.Provider>
</div>
);
}
I have the main code passed down to the Header
as props so I can have the toggler inside my header.
const Header = (props) => {
return (
<header>
<Navbar bg="dark" variant="dark" expand="lg" collapseOnSelect>
<Container className="nav_container">
<LinkContainer to="/">
<Navbar.Brand>Verdant</Navbar.Brand>
</LinkContainer>
<Slider // slider
onChange={props.toggleTheme}
checked={props.theme === "dark"}
/>
</Container>
</header>
);
};
The slider itself is a simple input
const Slider = () => {
return (
<div>
<label class={styles.switch}>
<input type="checkbox" />
<span class={styles.slider}></span>
</label>
</div>
);
};
The slider works fine. When I click on the slider it goes back and forth like it’s supposed to.
But when I inspect the page and I click on the slider, the id
isn’t changing from light
to dark
like it’s supposed to. It stays on light
no matter how many times I click it.