Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
React - navigating elements using window.onClick event listener

I was building a popup login window for my react project and I wanted to display it when I press the login button and close when I click outside the container. The outside area is actually a parent div which works as blurred overlay for its child element .I used useState for controlling boolean values and useRef hooks for controlling the display properties like I shown below.

<overlay onClick={()=>setPopupActive(false)}>
  <popup-window ref={displayPopupRef}>...some codes...</popup-window>..it only displays when the state is true
</overlay>

Since the I use useState on the parent element, it also affects the child element which is the popup window and closes it when ever I click on the child element. I tried to put stopPropagation on the child but it prevents some of my links which is a part of the parent component.

Since I don't find a cure for this issue, I use another approach which is by using window.onClick event listener...see the code below

useEffect(() => {
    window.onclick = (e) => {
        if (e.target.className === 'login-btn') 
        return  displayPopupRef.current.style.display = 'grid'
        if(['login-container-overlay','close-button'].includes(e.target.className))
        return displayPopupRef.current.style.display = 'none'
    }
}, [displayPopupRef])

and it works perfectly fine. I also use the same approach on searchbar and everythink seems to be okay and the console is clean...

Because of the reason that I am a beginner programmer, I keep wondering if it is the right way to do and is there any problem in using window.onclick event on such occasions.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!