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:
Erik Tiekstra
2024-10-03 15:34:20 +02:00
parent 451d461c7f
commit 676b763e67
8 changed files with 96 additions and 43 deletions

24
hooks/useClickOutside.ts Normal file
View 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])
}