DEMO

useClickOutside

Listen for click outside an element, useful for modals and tooltips.

Usage

import { useRef, useState } from 'react'
import { useClickOutside } from '@react-hooks-library/core'

function Dropdown(props: {
  isOpen: boolean
  setIsOpen: (isOpen: boolean) => void
}) {
  const { isOpen, setIsOpen } = props
  const ref = useRef(null)

  useClickOutside(ref, () => {
    setIsOpen(false)
  })

  if (!isOpen) return null

  return <div ref={ref}>This is a dropdown, click outside to close</div>
}

export function Demo() {
  const [isOpen, setIsOpen] = useState(false)

  return (
    <div>
      <div>
        <button onClick={() => setIsOpen(true)} disabled={isOpen}>
          Open Dropdown
        </button>
      </div>
      <div>
        <Dropdown isOpen={isOpen} setIsOpen={setIsOpen} />
      </div>
    </div>
  )
}

Type Declarations

declare type ClickOutsideEvents = Pick<
  WindowEventMap,
  | 'mousedown'
  | 'mouseup'
  | 'touchstart'
  | 'touchend'
  | 'pointerdown'
  | 'pointerup'
>
interface ClickOutsideOptions<E extends keyof ClickOutsideEvents> {
  event?: E
}
/**
 * Listen for clicks outside of an element.
 *
 * @param target
 * @param handler
 * @param options
 *
 * @see https://react-hooks-library.vercel.app/core/onClickOutside
 */
declare function useClickOutside<
  E extends keyof ClickOutsideEvents = 'pointerdown'
>(
  target: MaybeRef<Element | null | undefined>,
  handler: (evt: ClickOutsideEvents[E]) => void,
  options?: ClickOutsideOptions<E>
): _react_hooks_library_shared.Fn

Source

Source | Demo | Docs