shadcn-ahooks

useClickAway

Listen for click events outside the target element.

Overview

Listen for click events outside the target element.

Documentation and Examples

Installation

Open in
pnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useClickAway.json
npx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useClickAway.json
yarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useClickAway.json
bun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useClickAway.json

Listen for click events outside the target element.

Examples

Default usage

Custom DOM

Support multiple DOM

Listen for other events

Support multiple events

Support shadow DOM

API

type Target = Element | (() => Element) | React.MutableRefObject<Element>;
type DocumentEventKey = keyof DocumentEventMap;

useClickAway<T extends Event = Event>(
  onClickAway: (event: T) => void,
  target: Target | Target[],
  eventName?: DocumentEventKey | DocumentEventKey[]
);

Params

| Property | Description | Type | Default | | - | | - | | onClickAway | Trigger Function | (event: T) => void | - | | target | DOM elements or Ref or Function, support array | Target | Target[] | - | | eventName | Set the event to be listened, support array | DocumentEventKey | DocumentEventKey[] | click |

On this page