Skip to main content

useClickOutside

Trigger a callback when clicking outside the target area.

API

function useClickOutside<E extends Event = Event>(
target: EffectTarget<Node> | EffectTarget<Node>[],
listener: (event: E) => void,
options?: {
container?: EffectTarget<Element>;
eventName?: string | string[];
}
): void;

type Nullable<T> = T | undefined | null;
type EffectTarget<T> =
| Nullable<T>
| (() => Nullable<T>)
| { current: Nullable<T> };
  • target: Target node or nodes.
  • listener: Listener function.
  • options: Options object.
    • options.container: Container for binding events. Default is document.
    • options.eventName: Event name or names. Default is "mousedown".

Example

Count: 0
import React, { useRef, useState } from "react";
import { useClickOutside } from "@lilib/hooks";

function Example() {
const buttonRef = useRef(null);
const [count, setCount] = useState(0);

useClickOutside(buttonRef, () => {
setCount(count + 1);
});

return (
<>
<button ref={buttonRef}>Click outside</button> Count: {count}
</>
);
}

export default Example;