Skip to content

Instantly share code, notes, and snippets.

@rohanBagchi
Last active March 28, 2019 06:28
Show Gist options
  • Save rohanBagchi/4f6a4588737dd913ddf944dee95bc078 to your computer and use it in GitHub Desktop.
Save rohanBagchi/4f6a4588737dd913ddf944dee95bc078 to your computer and use it in GitHub Desktop.
Handling outside click with hook
import React, { useEffect } from 'react';
import get from 'lodash/get';
import noop from 'lodash/noop';
interface useOutsideClickHandlerProps {
node: any, // reference to top level node / element in the collapsible component.
onOutsideClick: (data?: any) => void,
onInsideClick?: (data?: any) => void,
}
const useOutsideClickHandler = ({ node, onOutsideClick, onInsideClick }: useOutsideClickHandlerProps) => {
onInsideClick = onInsideClick || noop;
const handleClick = (e: any) => {
const current: any = get(node, 'current');
if (!current) return;
if (current.contains(e.target)) {
// inside click
onInsideClick && onInsideClick();
return;
}
// outside click
onOutsideClick();
};
useEffect(() => {
document.addEventListener("mousedown", handleClick);
return () => {
document.removeEventListener("mousedown", handleClick);
};
}, []);
};
export default useOutsideClickHandler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment