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

  • By setting eventName, you can specify the event to be listened, Try click the right mouse.

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

PropertyDescriptionTypeDefault
onClickAwayTrigger Function(event: T) => void-
targetDOM elements or Ref or Function, support arrayTarget | Target[]-
eventNameSet the event to be listened, support arrayDocumentEventKey | DocumentEventKey[]click

On this page