Search code examples
reactjslocal-storagedarkmode

how to add dark mode with local storage in react


function Theme() {
  
  const toggleMode = (mode) => {
    if (mode === "add") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
  };
  const mode = localStorage.getItem("mode");
  return (
    <div className="theme_toggle">
        <div className="day_mode flex items-center" onClick={() => toggleMode("add")} >
          <Image src="/dark.svg" width="20" height="20" alt="night_mood" />
        </div>
        <div className="night_mode flex items-center" onClick={() => toggleMode("remove")} >
          <Image src="/day_white.svg" width="20" height="20" alt="day_mood" />
        </div>
    </div>
  )
}

export default Theme

I'm attempting to add a dark mode, and I've added it successfully. I want it to be saved after a refresh.


Solution

  • simply save and get it from localStorage and apply it to document in useEffect

    sth like this :

    function Theme() {
    
    
      useEffect(()=>{
        const mode = localStorage.getItem("mode");
      
      
         if(mode){
           document.documentElement.classList.add("dark");
        
         }
    
       },[])
      
      const toggleMode = (mode) => {
        if (mode === "add") {
          document.documentElement.classList.add("dark");
          localStorage.setItem('mode','dark')
        } else {
          document.documentElement.classList.remove("dark");
          localStorage.removeItem('mode')
          
        }
      };
      return (
        <div className="theme_toggle">
          <div className="day_mode flex items-center" onClick={() => toggleMode("add")} >
            <Image src="/dark.svg" width="20" height="20" alt="night_mood" />
          </div>
          <div className="night_mode flex items-center" onClick={() => toggleMode("remove")} >
            <Image src="/day_white.svg" width="20" height="20" alt="day_mood" />
          </div>
        </div>
      )
    }
    
    export default Theme