Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda