This gets a list of all elements with the tag "html", selects the first one, and then sets the "theme" attribute. You can then use read the localStorage and set the theme value accordingly.
You have provided an HTML tag with a theme attribute set to "dark." However, the theme attribute is not a standard HTML attribute, so it won’t have any effect on the page’s appearance by default. Use data-theme as attribute.
Create a state with a default theme value. Create a toggle function and call this function onClick of a button.
const toggleTheme = () => {
const newTheme = theme === 'light' ? 'dark' : 'light';
setTheme(newTheme);
localStorage.setItem('theme', newTheme); // Save the new theme preference to localStorage
document.documentElement.setAttribute('data-theme', newTheme); // Apply the selected theme class to the html element
Change <html theme="dark"> to <html class="dark">, and then add separate .light and .dark CSS classes. You can then create a custom hook that you can import into the component that has the toggle functionality.
Here the custom hook (useToggleTheme) initialises a state and returns a function. The function declares a new theme depending on the current state, changes the class on the document element (<html>), and then sets the new state with that value. This function is what your button calls.
3
Answers
You can just select the html element using vanilla js:
This gets a list of all elements with the tag "html", selects the first one, and then sets the "theme" attribute. You can then use read the localStorage and set the theme value accordingly.
See the documentation for setAttribute
You have provided an HTML tag with a theme attribute set to "dark." However, the theme attribute is not a standard HTML attribute, so it won’t have any effect on the page’s appearance by default. Use data-theme as attribute.
Create a state with a default theme value. Create a toggle function and call this function onClick of a button.
};
Change
<html theme="dark">
to<html class="dark">
, and then add separate.light
and.dark
CSS classes. You can then create a custom hook that you can import into the component that has the toggle functionality.Here the custom hook (
useToggleTheme
) initialises a state and returns a function. The function declares a new theme depending on the current state, changes the class on the document element (<html>
), and then sets the new state with that value. This function is what your button calls.