Skip to content

useClickAway

Calls a handler when interaction happens outside the target.

Calls a handler when interaction happens outside the target.

Import

import { useClickAway } from '@kamod-ch/hooks'

Live demo

Basic demo

Calls a handler when interaction happens outside the target.

Browser-only demo

This demo starts after the page mounts in the browser.
import { useRef, useState } from 'preact/hooks'
import { useClickAway } from '@kamod-ch/hooks'

export default function UseClickAwayDemo() {
  const ref = useRef<HTMLDivElement>(null)
  const [outsideClicks, setOutsideClicks] = useState(0)
  useClickAway(() => setOutsideClicks((value) => value + 1), ref)

  return (
    <div class="demo-click-away-wrap">
      <div ref={ref} class="demo-target-box">Click inside this box.</div>
      <button type="button">Click outside target</button>
      <p><strong>Outside clicks:</strong> {outsideClicks}</p>
    </div>
  )
}

API

TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
type DocumentEventKey = keyof DocumentEventMap;
declare const useClickAway: <T extends Event = Event>(onClickAway: (event: T) => void, target: BasicTarget | BasicTarget[], eventName?: DocumentEventKey | DocumentEventKey[]) => void;
export default useClickAway;
/

SSR considerations

This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.

Browser compatibility

Requires the corresponding browser API to exist in the current environment.