Last active
March 28, 2019 06:28
-
-
Save rohanBagchi/4f6a4588737dd913ddf944dee95bc078 to your computer and use it in GitHub Desktop.
Handling outside click with hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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