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. With 50+ projects delivered, we take you from first plan to a production-ready product, and we offer custom software development with fixed-price quotes. Book a free consultation, no commitment.