Skip to content
Advertisement

how to toggle between two css classes with react

I’m trying to toggle between two classes dark mode and normal mode.

THis is the vanilla js eventlistener

     const modeSwitch = document.querySelector('.mode-switch');

  modeSwitch.addEventListener('click', () => {
    document.documentElement.classList.toggle('dark');
    modeSwitch.classList.toggle('active');
  });

This is the button that when clicked on, switches between the two modes. how can I achieve this with react

     const [active, setActive] = useState(false)

     const handleToggle = () => {
      setActive(!active)
     }

 return (
    <button className="mode-switch" title="Switch Theme" onClick={handleToggle}>
          <svg className="moon" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" width="24" height="24" viewBox="0 0 24 24">
            <defs></defs>
            <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"></path>
          </svg>
        </button>
)

Advertisement

Answer

In this case you could use useRef:

const [active, setActive] = useState(false)
const modeRef = useRef();

const handleToggle = () => {
     modeRef.current.classList.toggle("dark")
}

return (
    <button ref={modeRef} className="mode-switch" title="Switch Theme" onClick={handleToggle}>
          <svg className="moon" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" width="24" height="24" viewBox="0 0 24 24">
            <defs></defs>
            <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"></path>
          </svg>
    </button>
)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement