useOutsidePointerDown
A custom hook that registers a callback to be called when a mouse or touch event occurs outside a specific element.
The provided callback is invoked whenever the user clicks the mouse or triggers a touch event outside the element specified by the ref.
On mobile environments it listens for touchstart, and on desktop it listens for mousedown.
Code
Interface
typescript
function useOutsidePointerDown<T extends HTMLElement>(
callback: (targetElement: T) => void,
options?: {
excludeRefs: React.RefObject<HTMLElement>[];
}
): { ref: React.RefObject<T | null> };
Options
| Name | Type | Default | Description |
|---|---|---|---|
callback | (targetElement: T) => void | - | Callback invoked when a pointer down event occurs outside the element |
options.excludeRefs | React.RefObject<HTMLElement>[] | - | Array of refs for elements to exclude from outside click/touch detection |
Returns
| Name | Type | Description |
|---|---|---|
ref | React.RefObject<T | null> | Ref to attach to the DOM element you want to monitor for outside clicks |
Remarks
References
Usage
typescript
import { useMemo, useState, useRef } from 'react';
import { useOutsidePointerDown } from '@modern-kit/react';
const Example = () => {
const [number, setNumber] = useState(0);
const excludeRef = useRef<HTMLDivElement>(null);
const { ref: targetRef } = useOutsidePointerDown<HTMLDivElement>(() => {
setNumber(number + 1);
}, {
excludeRefs: [excludeRef], // Array of refs for elements to exclude from outside click/touch detection.
});
const outerBoxStyle = useMemo(() => {
return { /* ... */ };
}, []);
const InnerBoxStyle = useMemo(() => {
return { /* ... */ };
}, []);
const ExcludeBoxStyle = useMemo(() => {
return { /* ... */ };
}, []);
return (
<div style={outerBoxStyle}>
<h3>Click outside the Target Box!<br />(Exclude Box is excluded from click detection.)</h3>
<p>number: {number}</p>
<div ref={targetRef} style={InnerBoxStyle}>
<h3>Target Box</h3>
</div>
<div ref={excludeRef} style={ExcludeBoxStyle}>
<h3>Exclude Box</h3>
</div>
</div>
);
};