fix(SW-272): now closing on click outside and also closing the mobile menu when changing to screensizes larger than mobile
This commit is contained in:
24
hooks/useClickOutside.ts
Normal file
24
hooks/useClickOutside.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { useEffect } from "react"
|
||||
|
||||
export default function useClickOutside(
|
||||
ref: React.RefObject<HTMLElement>,
|
||||
isOpen: boolean,
|
||||
callback: () => void
|
||||
) {
|
||||
useEffect(() => {
|
||||
function handleClickOutside(evt: Event) {
|
||||
const target = evt.target as HTMLElement
|
||||
if (ref.current && target && !ref.current.contains(target) && isOpen) {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener("click", handleClickOutside)
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("click", handleClickOutside)
|
||||
}
|
||||
}, [ref, isOpen, callback])
|
||||
}
|
||||
Reference in New Issue
Block a user