useClickOutside
UI/Interaction
A React hook that detects clicks outside a referenced element and executes a callback. Useful for implementing dropdown menus, modals, or any component that should close when the user clicks outside of it. Handles both mouse and touch events.
Installation
npm install @thibault.sh/hooks
API Reference
Signature
type Handler = (event: MouseEvent | TouchEvent) => void;
function useClickOutside<T extends HTMLElement = HTMLElement>(
ref: RefObject<T | null> | null,
handler: Handler
): void
Parameters
Name | Type | Description | Default |
---|---|---|---|
ref | RefObject<T | null> | null | React ref object pointing to the element to monitor for outside clicks. | - |
handler | Handler | Callback function executed when a click occurs outside the referenced element. Receives the mouse or touch event as parameter. | - |
Returns
void
This hook doesn't return anything. It sets up event listeners and executes the handler when clicks occur outside the referenced element.