useOutsideClick
The useOutsideClick
hook allows you to detect clicks that occur outside a specific DOM element, triggering a callback function when this happens.
Itβs ideal for closing modals, dropdowns, tooltips, or any component that should dismiss when clicking elsewhere on the page.
Syntaxβ
useOutsideClick(
ref: RefObject<HTMLElement>,
callback: (event: MouseEvent | TouchEvent) => void,
deps?: DependencyList
): void;
Parametersβ
Name | Type | Description |
---|---|---|
Refs (required) | RefObject<HTMLElement> | React ref to the element to detect outside clicks from |
Callback (required) | (event: MouseEvent or TouchEvent) => void | Function to run when an outside click is detected. |
deps (optional) | DependencyList | Dependency array for when to refresh the callback behavior |
Exampleβ
It listens for clicks outside the box and automatically hides it whenever you click anywhere else on the page.