Hooks
/ API Reference
Hooks
/ API Reference

useClickAway

A hook that calls a callback when the user clicks outside of a given element.

Tip

Use active if multiple components with the same hook are mounted. Then only the ones with active will trigger. No need to stop popagation in this case.

The Gist

'use client'
import { useClickAway } from '@weser/hooks'

function Component() {
  const ref = useRef<HTMLDivElement>(null)

  useClickAway(ref, () => console.log('clicked outside'))

  return <div ref={ref}>Click me</div>
}

Parameters

ParameterTypeDefaultDescription
refRefObject (new tab)The ref object to use.
callback() => voidThe callback to call when clicked away.
activeboolean?trueWhether the hook is active.
On this page