javascriptreactjsuse-refqueryselector

document.querySelector('something').addEventListener(), how do I achieve the functionality of this snippet on reactJS


I was trying to achieve Diprella Login design to create my own personal login page, looking through multiple sources, I found a CSS and Html design for the page however, I'm trying to implement it on reactJs. and I'm facing an Issue where every time I reload the page all components disappear. after multiple iterations of trial and error, I narrowed the issue down to this following snippet of the code

document.querySelector('.img-btn').addEventListener('click', function()
{
  document.querySelector('.cont').classList.toggle('s-signup')
}
);

is there any way to solve this issue, from what I've gathered, useRef can be used instead of querySelector. but since I'm new to react as well front end Development, I'm finding it hard to solve the issue. Any Help would be greatly appreciated!

I tried using onClick and created a function which returns

  document.querySelector('.cont').classList.toggle('s-signup')

the issue still pertains where reload disappears all the existing components


Solution

  • Toggling a class on click can be done by storing a boolean in state. In the below example I use a state hook.

    Codesandbox demo

    import { useState } from 'react';
    
    function App() {
    
      const [signUp, setSignUp] = useState(false)
    
      return (
        <div className={`cont${(signUp ? " s-signup" : "")}`}>
    
          <img className="img-btn" src="..." onClick={() => setSignUp(!signUp)} />
        </div>
      );
    }