4

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>
)

1 Answer 1

1

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>
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.