Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] - useOnClickOutside cannot be trigged during capture phase #554

Closed
metav-drimz opened this issue Mar 21, 2024 · 1 comment · Fixed by #552 · May be fixed by EchoSkorJjj/UI#255
Closed

[BUG] - useOnClickOutside cannot be trigged during capture phase #554

metav-drimz opened this issue Mar 21, 2024 · 1 comment · Fixed by #552 · May be fixed by EchoSkorJjj/UI#255
Labels
bug Something isn't working

Comments

@metav-drimz
Copy link

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:

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_
@metav-drimz metav-drimz added the bug Something isn't working label Mar 21, 2024
juliencrn added a commit that referenced this issue Mar 21, 2024
* Support missing refs (fixes #531)

* Add support for focus event to `useOnClickOutside` (Fixes: #522)

* Expose `AddEventListenerOptions` in `useOnClickOutside` (Fixes #554 from @metav-drimz)
@metav-drimz
Copy link
Author

thank u! I feel it could be useful in other hooks too...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
1 participant