This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
website/hooks/useClickOutsideAlerter.ts

23 lines
579 B
TypeScript
Raw Normal View History

import { useEffect } from 'react'
export const useClickOutsideAlerter = (
ref: React.RefObject<HTMLElement>,
callback: () => void
): void => {
useEffect(() => {
const handleClickOutside = (event: MouseEvent): void => {
if (
event.target != null &&
ref.current != null &&
!ref.current.contains(event.target as Node)
) {
callback()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
}
}, [ref, callback])
}