react react-hook ironman30
useClickOutside
A Hook to trigger callback when user clicks on outside of the target
LINKS
鐵人賽連結
function useClickOutside(cb) {
const ref = useRef()
useEffect(() => {
const handleClick = (event) => {
const target = event.target
const isInside = ref.current.contains(target)
if (!isInside) {
cb()
}
}
document.addEventListener("click", handleClick)
return () => {
document.removeEventListener("click", handleClick)
}
}, [])
return ref
}
Params
name |
type |
description |
---|
cb | function | callback function to fire on condition |
Return
name |
type |
description |
---|
ref | Object | suppose to attach on DOM element |
Example