You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We have a use-case where we needed to useOnClickOutside with EventListenerOptions
The reason is that we had to close a popup but the event target also had preventDefault and stopPropagations so we had to trigger the event on the capture phase
To Reproduce
.
Expected behavior
Our solution:
import type { RefObject } from 'react';
import { useEventListener } from 'usehooks-ts';
type EventType = 'mousedown' | 'mouseup' | 'touchstart' | 'touchend';
export function useOnClickOutside<T extends HTMLElement = HTMLElement>(
ref: RefObject<T> | RefObject<T>[],
handler: (event: MouseEvent | TouchEvent) => void,
eventType: EventType = 'mousedown',
eventListenerOptions: AddEventListenerOptions = {}
): void {
useEventListener(
eventType,
(event) => {
const target = event.target as Node;
// Do nothing if the target is not connected element with document
if (!target || !target.isConnected) {
return;
}
const isOutside = Array.isArray(ref)
? ref.every((r) => r.current && !r.current.contains(target))
: ref.current && !ref.current.contains(target);
if (isOutside) {
handler(event);
}
},
undefined,
eventListenerOptions
);
}
### Additional context
_No response_
The text was updated successfully, but these errors were encountered:
* Support missing refs (fixes#531)
* Add support for focus event to `useOnClickOutside` (Fixes: #522)
* Expose `AddEventListenerOptions` in `useOnClickOutside` (Fixes#554 from @metav-drimz)
Describe the bug
We have a use-case where we needed to useOnClickOutside with EventListenerOptions
The reason is that we had to close a popup but the event target also had preventDefault and stopPropagations so we had to trigger the event on the capture phase
To Reproduce
.
Expected behavior
Our solution:
The text was updated successfully, but these errors were encountered: