Skip to content

Instantly share code, notes, and snippets.

@edwardsmoses
Created January 26, 2021 19:41
Show Gist options
  • Save edwardsmoses/ebba3ea7cf136ac93f8d0d33a3e3d2a1 to your computer and use it in GitHub Desktop.
Save edwardsmoses/ebba3ea7cf136ac93f8d0d33a3e3d2a1 to your computer and use it in GitHub Desktop.
Hook to Capture Click Outside in React
import {useToCaptureClickOutside} from '../hooks/useToCaptureClickOutside';
const [isOpen, setOpen] = useState(false);
const closeOutsideNodeRef = useToCaptureClickOutside(isOpen, () => setOpen(false));
<div className="ml-3 relative" ref={closeOutsideRef}>
{/* rest of code */}
</div>
import {useState, useEffect, useRef, MutableRefObject} from 'react';
/**
* Capture click outside
*
* How it works:
*
* It holds the ref of the element (modal, dropdown, popup).
*
* Then adds a event listener to the document (Which checks if a click event is outside the the elementRef)
*
* When The Click is outside, it closes the element (using the callBack function - callBackOnClickOutside)
*
* Source and Explanation:
* https://medium.com/@pitipatdop/little-neat-trick-to-capture-click-outside-with-react-hook-ba77c37c7e82
*
* @param isOpen
* @param callBackOnClickOutside - function to be called when user clicks outside...
*/
export const useToCaptureClickOutside = (
isOpen: boolean,
callBackOnClickOutside: () => void,
): MutableRefObject<HTMLDivElement> => {
const node = useRef<HTMLDivElement>();
const handleClickOutside = (e) => {
if (node.current.contains(e.target)) {
// inside click
return;
}
// outside click
callBackOnClickOutside();
};
useEffect(() => {
if (isOpen) {
document.addEventListener('mousedown', handleClickOutside);
} else {
document.removeEventListener('mousedown', handleClickOutside);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [isOpen]);
return node;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment