useOnClickOutside
Events & gesturesA React hook for detecting clicks outside of specified elements
Install
$ npm install @usefy/use-on-click-outsideQuick start
useOnClickOutside.tsx
import { useOnClickOutside } from "@usefy/use-on-click-outside";
import { useRef, useState } from "react";
function Modal({ onClose }: { onClose: () => void }) {
const modalRef = useRef<HTMLDivElement>(null);
useOnClickOutside(modalRef, () => onClose());
return (
<div className="overlay">
<div ref={modalRef} className="modal">
Click outside to close
</div>
</div>
);
}API reference
useOnClickOutside(ref, handler, options?)
A hook that detects clicks outside of specified element(s).
Parameters
| Parameter | Type | Description |
|---|---|---|
ref | RefTarget<T> | Single ref or array of refs to detect outside clicks for |
handler | OnClickOutsideHandler | Callback function called when a click outside is detected |
options | UseOnClickOutsideOptions | Configuration options |
Options
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Whether the event listener is active |
capture | boolean | true | Use event capture phase (immune to stopPropagation) |
eventType | MouseEventType | "mousedown" | Mouse event type to listen for |
touchEventType | TouchEventType | "touchstart" | Touch event type to listen for |
detectTouch | boolean | true | Whether to detect touch events (mobile support) |
excludeRefs | RefObject<HTMLElement>[] | [] | Refs to exclude from outside click detection |
shouldExclude | (target: Node) => boolean | undefined | Custom function to determine if target should be excluded |
eventTarget | Document | HTMLElement | Window | null | document | The event target to attach listeners to |
Types
type ClickOutsideEvent = MouseEvent | TouchEvent;
type OnClickOutsideHandler = (event: ClickOutsideEvent) => void;
type MouseEventType =
| "mousedown"
| "mouseup"
| "click"
| "pointerdown"
| "pointerup";
type TouchEventType = "touchstart" | "touchend";
type RefTarget<T extends HTMLElement> =
| React.RefObject<T | null>
| Array<React.RefObject<HTMLElement | null>>;
Returns
void
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.