Skip to content Skip to sidebar Skip to footer

React Hooks: UseEffect For Modal Event Listener

I have a modal dialog that I want to close if the user clicks outside of the modal. I have written the following useEffect code but I run into following issue: The modal dialog co

Solution 1:

I found a solution that does not require any sort of storing old props.

The useEffect call looks like this:

useEffect( () => {
        const onClickOutside = () => onCloseModal();
        window.addEventListener( 'click', onClickOutside, false );
        return () => window.removeEventListener( 'click', onClickOutside );
    }, [] );

Adding the following click listener to the modal directly will stop the window click-listener from being called if the user clicked inside the modal.

<div
    className={`modal ${ classes }`}
    onClick={event => event.stopPropagation()}
    role="presentation"
>
   {children}
</div>`

I also added the role presentation to make the modal more accessible and aria-conform.


Solution 2:

You can check parent of modal from the event.target. If the current target is within the modal then return.

You can use closest to do that.

See the following solution.

...

    if (event.target.closest( '.singleton-modal' ) || event.target.classList.contains('singleton-modal')) {
       return;
    }

...

Post a Comment for "React Hooks: UseEffect For Modal Event Listener"