Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add dark class add and save after refresh in react

how i can save dark class after refresh

import Image from 'next/image'
import React from '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 am adding the cdark class to html tage but i want after refresh it will be save.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading