Created
January 17, 2023 14:26
-
-
Save ruvasik/20f80462e353cc57dfc8f9740bd5240c to your computer and use it in GitHub Desktop.
React typed hook useOnClickOutside
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 React from "react"; | |
export default function useOnClickOutside( | |
ref: React.RefObject<HTMLElement>, | |
handler: (event: TouchEvent | MouseEvent) => void | |
) { | |
React.useEffect(() => { | |
const listener = (event: TouchEvent | MouseEvent) => { | |
if (!ref.current || ref.current.contains(event.target as HTMLElement)) { | |
return; | |
} | |
handler(event); | |
}; | |
document.addEventListener("mousedown", listener); | |
document.addEventListener("touchstart", listener); | |
return () => { | |
document.removeEventListener("mousedown", listener); | |
document.removeEventListener("touchstart", listener); | |
}; | |
}, [ref, handler]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment