Last active
September 23, 2022 19:38
-
-
Save lahin31/32013aefaab11819b708cfaf933c9c1b to your computer and use it in GitHub Desktop.
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
// useClickOutside.js | |
import { useEffect, useRef } from "react"; | |
function useClickOutside(elRef, callback) { | |
const callbackRef = useRef(); | |
callbackRef.current = callback; | |
useEffect(() => { | |
const handleClickOutside = (e) => { | |
if (!elRef?.current?.contains(e.target) && callbackRef.current) { | |
callbackRef.current(e); | |
} | |
}; | |
document.addEventListener("mousedown", handleClickOutside); | |
return () => { | |
document.removeEventListener("mousedown", handleClickOutside); | |
}; | |
}, [callbackRef, elRef]); | |
} | |
export default useClickOutside; | |
// Drawer.js | |
const sideDrawer = useRef(null); | |
const onClickOutside = () => { | |
setShowDrawer(false); | |
}; | |
useClickOutside(sideDrawer, onClickOutside); | |
<div ref={sideDrawer} className={showDrawer ? "side-drawer open" : "side-drawer"} /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment