Außenklick -Haken reagieren
import { useEffect, MutableRefObject } from 'react'
export const useOutsideClick = <T extends Array<MutableRefObject<any>>>(
ref: T,
callback: () => void
): void => {
useEffect(() => {
const handler = (event: MouseEvent): void => {
// Check if the mouse click was within the element's ref.
if (!ref || ref.length === 0) return
const node = ref.find((x) => x?.current?.contains(event?.target as Node))
if (!node) {
callback()
}
}
window.addEventListener('mousedown', handler)
return (): void => {
window.removeEventListener('mousedown', handler)
}
}, [ref, callback])
}
// Usage (it should be in the component*)
const firstRef = useRef(null)
const secondRef = useRef(null)
const handleClick = () => { console.log('Clicked outside ref') }
useOutsideClick([firstRef, secondRef], handleClick)
Injury