Skip to content
usefy

useOnClickOutside

Events & gestures

A React hook for detecting clicks outside of specified elements

Install

$ npm install @usefy/use-on-click-outside

Quick 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

ParameterTypeDescription
refRefTarget<T>Single ref or array of refs to detect outside clicks for
handlerOnClickOutsideHandlerCallback function called when a click outside is detected
optionsUseOnClickOutsideOptionsConfiguration options

Options

OptionTypeDefaultDescription
enabledbooleantrueWhether the event listener is active
capturebooleantrueUse event capture phase (immune to stopPropagation)
eventTypeMouseEventType"mousedown"Mouse event type to listen for
touchEventTypeTouchEventType"touchstart"Touch event type to listen for
detectTouchbooleantrueWhether to detect touch events (mobile support)
excludeRefsRefObject<HTMLElement>[][]Refs to exclude from outside click detection
shouldExclude(target: Node) => booleanundefinedCustom function to determine if target should be excluded
eventTargetDocument | HTMLElement | Window | nulldocumentThe 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.

More in events & gestures