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.
CodePudding user response:
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