webapp/src/utils/useOutsideClickHandler.ts

30 lines
837 B
TypeScript
Raw Normal View History

import { onCleanup, onMount } from 'solid-js'
type Options = {
containerRef: { current: HTMLElement }
handler: () => void
2023-05-03 16:13:48 +00:00
// if predicate is present
// handler is called only if predicate function returns true
predicate?: () => boolean
}
export const useOutsideClickHandler = (options: Options) => {
const { predicate, containerRef, handler } = options
const handleClickOutside = (event: MouseEvent & { target: Element }) => {
if (predicate && !predicate()) {
return
}
if (event.target === containerRef.current || containerRef.current?.contains(event.target)) {
return
}
2022-11-10 12:50:47 +00:00
handler()
}
onMount(() => {
document.addEventListener('click', handleClickOutside, { capture: true })
onCleanup(() => document.removeEventListener('click', handleClickOutside, { capture: true }))
})
}