useClickAway
Listen for clicks outside of an element. Useful for modal or dropdown.
Alias
useClickAway is an alias for useClickOutside. They have identical functionality and API.
Usage
Live Editor
function Demo() { const [visible, setVisible] = useState(false); const modalRef = useRef<HTMLDivElement>(null); useClickAway(modalRef, () => { setVisible(false); }); return ( <div> <button onClick={() => setVisible(true)}> Open Modal</button> {visible && ( <div ref={modalRef} style={{ position: "fixed", left: "50%", top: "50%", transform: "translate(-50%,-50%)", width: 420, maxWidth: "100%", zIndex: 10, border: "1px solid var(--c-input-border)", background: "var(--c-bg)", }} > <div style={{ padding: "0.4em 2em", boxShadow: "2px 2px 10px var(--c-box-shadow)", }} > <p style={{ fontWeight: 700, fontSize: "1.4rem", marginBottom: "2rem", }} > Demo Modal </p> <p>Click outside of the modal to close it.</p> </div> </div> )} </div> ); };
Result
Loading...
API
useClickOutside
Returns
void
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| target | dom element | BasicTarget<Element> (Required) | - |
| handler | listener fucntion | (evt: EventType) => void (Required) | - |
| enabled | whether the listener fucntion is enabled | boolean | undefined | - |
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;
EventType
export type EventType = MouseEvent | TouchEvent;