Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda