skip to Main Content

I want to select the theme value to change it based on localStorage value to set the light/dark theme, how can I do that in React?

image

I know I can use Ref hook in a component but how can I select a dom element in index.html?

3

Answers


  1. You can just select the html element using vanilla js:

    document.getElementsByTagName("html")[0].setAttribute("theme","dark")
    

    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

    Login or Signup to reply.
  2. 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
    

    };

    Login or Signup to reply.
  3. 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.

    const { useState } = React;
    
    function useToggleTheme() {
    
      const [theme, setTheme] = useState('dark');
    
      function toggleTheme() {
        const newTheme = theme === 'dark' ? 'light' : 'dark';
        document.documentElement.className = newTheme;
        setTheme(newTheme);
      }
    
      return toggleTheme;
    
    }
    
    function Example() {
    
      const toggleTheme = useToggleTheme();
    
      return (
        <div>
          <button onClick={toggleTheme}>
            Toggle theme
          </button>
        </div>
      );
    
    }
    
    const node = document.getElementById('root');
    const root = ReactDOM.createRoot(node);
    root.render(<Example />);
    .dark { background-color: darkgray; color: white; }
    .light { background-color: white; color: darkgray; }
    <html class="dark">
    <body>
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search