Detects clicks outside a referenced element to close dropdowns or modals.
import { useEffect, useRef } from class=class="text-emerald-400">"text-emerald-400">'react'
function useClickOutside<T extends HTMLElement>(callback: () => void) {
const ref = useRef<T>(null)
useEffect(() => {
function handleClick(event: MouseEvent) {
if (ref.current && !ref.current.contains(event.target as Node)) {
callback()
}
}
document.addEventListener(class=class="text-emerald-400">"text-emerald-400">'mousedown', handleClick)
return () => document.removeEventListener(class=class="text-emerald-400">"text-emerald-400">'mousedown', handleClick)
}, [callback])
return ref
}
export default useClickOutsideAttach to a dropdown container: const ref = useClickOutside<HTMLDivElement>(() => setOpen(false)). Pass the ref to the wrapper element. Clicking outside will trigger the callback.
Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.