Created
August 16, 2025 06:50
-
-
Save pH-7/d97d318488a1e7fed1a41b65566efa95 to your computer and use it in GitHub Desktop.
React custom hook to handle click outside events for modals and dropdowns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, RefObject } from 'react'; | |
/** | |
* Custom hook to handle click outside events for modals and dropdowns | |
* @param ref - Reference to the element to detect clicks outside of | |
* @param handler - Function to call when click outside is detected | |
* @param enabled - Whether the click outside detection is enabled (default: true) | |
*/ | |
export const useClickOutside = ( | |
ref: RefObject<HTMLElement>, | |
handler: () => void, | |
enabled: boolean = true | |
) => { | |
useEffect(() => { | |
if (!enabled) return; | |
const handleClickOutside = (event: MouseEvent) => { | |
if (ref.current && !ref.current.contains(event.target as Node)) { | |
handler(); | |
} | |
}; | |
// Add event listener to document | |
document.addEventListener('mousedown', handleClickOutside); | |
// Cleanup event listener on unmount | |
return () => { | |
document.removeEventListener('mousedown', handleClickOutside); | |
}; | |
}, [ref, handler, enabled]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment