useClickOutside
Hook to listen and execute an action when there is a click outside an element.
Demo
INFO
The component renders a button to open a dropdown. When dropdown is open, the button is disabled. To close dropdown is used useClickOutside that keeps a reference to dropdown container and closes dropdown when there is a click outside dropdown container.
Loading demo…
Show source code
tsx
import { useRef, useState } from "react"
import { useClickOutside } from "../../../..";
import { Dropdown } from "./Dropdown";
export const UseClickOutside = () => {
const [isOpen, setIsOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useClickOutside(ref, () => setIsOpen(false));
return <div style={{ margin: "0 auto", width: "fit-content" }}>
<button onClick={() => setIsOpen(true)} disabled={isOpen}>Dropdown</button>
<div ref={ref}>
{
isOpen && <Dropdown/>
}
</div>
</div>
}Types
UseClickOutsideProps
Parameters accepted by useClickOutside.
| Property | Type | Required | Description |
|---|---|---|---|
target | RefObject<HTMLElement> \| HTMLElement | ✓ | The element to monitor. Accepts either a React RefObject<HTMLElement> or a direct HTMLElement reference. Click events originating inside this element (or on the element itself) are ignored; only clicks outside it trigger handler. |
handler | (evt: Event) => void | ✓ | Callback invoked whenever a click event is detected outside the target element. Receives the native {@link Event} that triggered the outside-click detection. |
