Skip to main content

Function: useOutsideClick()

useOutsideClick(ref, callback): void

Defined in: use-outside-click.ts:24

A custom React hook that triggers a callback function when a click or touch event occurs outside the specified element.

This hook is useful for handling scenarios like closing dropdowns, modals, or tooltips when clicking outside the component.

Parameters​

ref​

RefObject<HTMLElement>

A React ref object pointing to the element to detect outside clicks for.

callback​

() => void

The callback function to execute when a click or touch event occurs outside the specified element.

Returns​

void

Example​

const ref = useRef<HTMLDivElement>(null);
useOutsideClick(ref, () => {
console.log("Clicked outside the component");
});

return <div ref={ref}>Click outside this element</div>;

For a live, editable example, see the useOutsideClick docs page.