Created
May 26, 2022 18:37
-
-
Save LeeCheneler/1fa695bddf24cb2a3492c7fecf5c6550 to your computer and use it in GitHub Desktop.
use-outside-click
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 const useOutsideClick = ( | |
refs: React.MutableRefObject<any>[], | |
callback: () => void | |
) => { | |
React.useEffect(() => { | |
const handleClick = (e: MouseEvent) => { | |
if ( | |
refs.every( | |
(ref) => | |
ref.current && | |
!ref.current.contains(e.target as Node) && | |
ref.current !== e.target | |
) | |
) { | |
callback(); | |
} | |
}; | |
document.addEventListener("click", handleClick); | |
return () => { | |
document.removeEventListener("click", handleClick); | |
}; | |
}, [refs, callback]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment