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.