MCPcopy
hub / github.com/ibelick/motion-primitives / useClickOutside

Function useClickOutside

hooks/useClickOutside.tsx:3–24  ·  view source on GitHub ↗
(
  ref: RefObject<T>,
  handler: (event: MouseEvent | TouchEvent) => void
)

Source from the content-addressed store, hash-verified

1import { RefObject, useEffect } from 'react';
2
3function useClickOutside<T extends HTMLElement>(
4 ref: RefObject<T>,
5 handler: (event: MouseEvent | TouchEvent) => void
6): void {
7 useEffect(() => {
8 const handleClickOutside = (event: MouseEvent | TouchEvent) => {
9 if (!ref || !ref.current || ref.current.contains(event.target as Node)) {
10 return;
11 }
12
13 handler(event);
14 };
15
16 document.addEventListener('mousedown', handleClickOutside);
17 document.addEventListener('touchstart', handleClickOutside);
18
19 return () => {
20 document.removeEventListener('mousedown', handleClickOutside);
21 document.removeEventListener('touchstart', handleClickOutside);
22 };
23 }, [ref, handler]);
24}
25
26export default useClickOutside;

Callers 4

ToolbarExpandableFunction · 0.85
MorphingDialogContentFunction · 0.85
MorphingPopoverContentFunction · 0.85
ToolbarDynamicFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected