Last active
November 3, 2021 19:04
-
-
Save anpct/556ca146c7acdff05e622585c9e36f03 to your computer and use it in GitHub Desktop.
useListener
This file contains 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 { useEffect, useRef } from "react"; | |
const useListener = (outsideFunction) => { | |
const ref = useRef(); | |
useEffect(() => { | |
const handleClick = (event) => { | |
if (ref.current && ref.current.contains(event.target)) { | |
return; | |
} | |
outsideFunction(); | |
}; | |
document.addEventListener("mousedown", handleClick); | |
return () => { | |
document.removeEventListener("mousedown", handleClick); | |
}; | |
}, [outsideFunction]); | |
return ref; | |
}; | |
export default useListener; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment