useClickOutside
React hook to detect clicks and touches outside a referenced element with customizable event listeners and callbacks.
Demo
Menu is closed
Usage
Simple — fires when the user clicks outside the ref'd element:
Object form — custom events:
Parameters
Simple form
| Parameter | Type | Description |
|---|---|---|
callback | (event: MouseEvent | TouchEvent) => void | Fires when a click or touch occurs outside the ref'd element. |
Object form
| Property | Type | Default | Description |
|---|---|---|---|
onClick | (event: MouseEvent | TouchEvent) => void | — | Fires when a click or touch occurs outside the ref'd element. |
events | string[] | ['mousedown', 'touchstart'] | DOM events to listen for. |
Return Values
Returns a React.RefObject<T>. Attach it to the element you want to treat as the boundary.