I’m trying to toggle between two classes dark mode and normal mode.
THis is the vanilla js eventlistener
JavaScript
x
7
1
const modeSwitch = document.querySelector('.mode-switch');
2
3
modeSwitch.addEventListener('click', () => {
4
document.documentElement.classList.toggle('dark');
5
modeSwitch.classList.toggle('active');
6
});
7
This is the button that when clicked on, switches between the two modes. how can I achieve this with react
JavaScript
1
15
15
1
const [active, setActive] = useState(false)
2
3
const handleToggle = () => {
4
setActive(!active)
5
}
6
7
return (
8
<button className="mode-switch" title="Switch Theme" onClick={handleToggle}>
9
<svg className="moon" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" width="24" height="24" viewBox="0 0 24 24">
10
<defs></defs>
11
<path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"></path>
12
</svg>
13
</button>
14
)
15
Advertisement
Answer
In this case you could use useRef
:
JavaScript
1
16
16
1
const [active, setActive] = useState(false)
2
const modeRef = useRef();
3
4
const handleToggle = () => {
5
modeRef.current.classList.toggle("dark")
6
}
7
8
return (
9
<button ref={modeRef} className="mode-switch" title="Switch Theme" onClick={handleToggle}>
10
<svg className="moon" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" width="24" height="24" viewBox="0 0 24 24">
11
<defs></defs>
12
<path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"></path>
13
</svg>
14
</button>
15
)
16