Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | 41x 29x 29x 1x 28x 2x 26x 5x 3x 23x 24x 5x 18x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 48x 48x 7x 41x 41x 48x 28x 17x 48x 1x 1x 48x 48x 40x 41x 41x 41x 40x | import { useEffect, useRef } from "react";
/**
* Event types for click outside detection (mouse + touch)
*/
export type ClickOutsideEvent = MouseEvent | TouchEvent;
/**
* Handler function type for click outside events
*/
export type OnClickOutsideHandler = (event: ClickOutsideEvent) => void;
/**
* Mouse event type options
*/
export type MouseEventType =
| "mousedown"
| "mouseup"
| "click"
| "pointerdown"
| "pointerup";
/**
* Touch event type options
*/
export type TouchEventType = "touchstart" | "touchend";
/**
* Ref target type - supports single ref or array of refs
* Array accepts mixed element types (e.g., [buttonRef, divRef])
*/
export type RefTarget<T extends HTMLElement = HTMLElement> =
| React.RefObject<T | null>
| Array<React.RefObject<HTMLElement | null>>;
/**
* Options for useOnClickOutside hook
*/
export interface UseOnClickOutsideOptions {
/**
* Whether the event listener is enabled
* @default true
*/
enabled?: boolean;
/**
* Whether to use event capture phase.
* When true, the handler is called before the event reaches the target element,
* making it immune to stopPropagation calls.
* @default true
*/
capture?: boolean;
/**
* Mouse event type to listen for
* @default 'mousedown'
*/
eventType?: MouseEventType;
/**
* Touch event type to listen for
* @default 'touchstart'
*/
touchEventType?: TouchEventType;
/**
* Whether to detect touch events (for mobile support)
* @default true
*/
detectTouch?: boolean;
/**
* Array of refs to exclude from outside click detection.
* Clicks on these elements will not trigger the handler.
*/
excludeRefs?: Array<React.RefObject<HTMLElement | null>>;
/**
* Custom function to determine if a target should be excluded.
* Return true to ignore clicks on the target element.
* @param target - The clicked element
* @returns Whether to exclude this element from triggering the handler
*/
shouldExclude?: (target: Node) => boolean;
/**
* The event target to attach listeners to
* @default document
*/
eventTarget?: Document | HTMLElement | Window | null;
}
/**
* Normalizes ref input to always return an array of refs
*/
function normalizeRefs<T extends HTMLElement>(
ref: RefTarget<T>
): Array<React.RefObject<HTMLElement | null>> {
return Array.isArray(ref) ? ref : [ref];
}
/**
* Checks if a click event occurred outside of all specified elements
*/
function isClickOutside(
event: ClickOutsideEvent,
refs: Array<React.RefObject<HTMLElement | null>>,
excludeRefs: Array<React.RefObject<HTMLElement | null>>,
shouldExclude?: (target: Node) => boolean
): boolean {
const target = event.target as Node;
// Check if target exists in DOM
if (!target || !target.isConnected) {
return false;
}
// Check custom exclude function
if (shouldExclude?.(target)) {
return false;
}
// Check exclude refs
for (const excludeRef of excludeRefs) {
if (excludeRef.current?.contains(target)) {
return false;
}
}
// Check target refs - if clicked inside any of them, it's not an outside click
for (const ref of refs) {
if (ref.current?.contains(target)) {
return false;
}
}
return true;
}
/**
* Detects clicks outside of specified element(s) and calls the provided handler.
* Useful for closing modals, dropdowns, popovers, and similar UI components.
*
* @param ref - Single ref or array of refs to detect outside clicks for
* @param handler - Callback function called when a click outside is detected
* @param options - Configuration options for the event listener
*
* @example
* ```tsx
* // Basic usage - close modal on outside click
* function Modal({ isOpen, onClose }) {
* const modalRef = useRef<HTMLDivElement>(null);
*
* useOnClickOutside(modalRef, () => onClose(), { enabled: isOpen });
*
* if (!isOpen) return null;
*
* return (
* <div className="overlay">
* <div ref={modalRef} className="modal">
* Modal content
* </div>
* </div>
* );
* }
* ```
*
* @example
* ```tsx
* // Multiple refs - button and dropdown menu
* function Dropdown() {
* const [isOpen, setIsOpen] = useState(false);
* const buttonRef = useRef<HTMLButtonElement>(null);
* const menuRef = useRef<HTMLDivElement>(null);
*
* useOnClickOutside(
* [buttonRef, menuRef],
* () => setIsOpen(false),
* { enabled: isOpen }
* );
*
* return (
* <>
* <button ref={buttonRef} onClick={() => setIsOpen(!isOpen)}>
* Toggle
* </button>
* {isOpen && (
* <div ref={menuRef}>Dropdown content</div>
* )}
* </>
* );
* }
* ```
*
* @example
* ```tsx
* // With exclude refs - ignore specific elements
* function ModalWithPortal({ isOpen, onClose }) {
* const modalRef = useRef<HTMLDivElement>(null);
* const toastRef = useRef<HTMLDivElement>(null);
*
* useOnClickOutside(modalRef, onClose, {
* enabled: isOpen,
* excludeRefs: [toastRef], // Clicks on toast won't close modal
* });
*
* return (
* <>
* {isOpen && <div ref={modalRef}>Modal</div>}
* <div ref={toastRef}>Toast notification</div>
* </>
* );
* }
* ```
*
* @example
* ```tsx
* // With custom exclude function
* useOnClickOutside(ref, handleClose, {
* shouldExclude: (target) => {
* // Ignore clicks on elements with specific class
* return (target as Element).closest?.('.ignore-outside-click') !== null;
* },
* });
* ```
*/
export function useOnClickOutside<T extends HTMLElement = HTMLElement>(
ref: RefTarget<T>,
handler: OnClickOutsideHandler,
options: UseOnClickOutsideOptions = {}
): void {
const {
enabled = true,
capture = true,
eventType = "mousedown",
touchEventType = "touchstart",
detectTouch = true,
excludeRefs = [],
shouldExclude,
eventTarget,
} = options;
// Store handler in ref to avoid re-registering event listeners
const handlerRef = useRef<OnClickOutsideHandler>(handler);
// Store shouldExclude in ref to avoid re-registering event listeners
const shouldExcludeRef = useRef(shouldExclude);
// Store excludeRefs in ref to avoid re-registering event listeners
const excludeRefsRef = useRef(excludeRefs);
// Store ref in a ref to avoid re-registering when array is passed inline
const refRef = useRef(ref);
// Update refs when values change
handlerRef.current = handler;
shouldExcludeRef.current = shouldExclude;
excludeRefsRef.current = excludeRefs;
refRef.current = ref;
useEffect(() => {
// SSR check
Iif (typeof document === "undefined") {
return;
}
// Don't add listener if disabled
if (!enabled) {
return;
}
// Normalize refs to array (use refRef.current to get latest value)
const normalizedRefs = normalizeRefs(refRef.current);
// Get the event target (default to document)
const target = eventTarget ?? document;
// Internal handler for mouse events
const handleMouseEvent = (event: Event) => {
if (
isClickOutside(
event as MouseEvent,
normalizedRefs,
excludeRefsRef.current,
shouldExcludeRef.current
)
) {
handlerRef.current(event as MouseEvent);
}
};
// Internal handler for touch events
const handleTouchEvent = (event: Event) => {
Eif (
isClickOutside(
event as TouchEvent,
normalizedRefs,
excludeRefsRef.current,
shouldExcludeRef.current
)
) {
handlerRef.current(event as TouchEvent);
}
};
// Add event listeners
target.addEventListener(eventType, handleMouseEvent, { capture });
if (detectTouch) {
target.addEventListener(touchEventType, handleTouchEvent, { capture });
}
// Cleanup
return () => {
target.removeEventListener(eventType, handleMouseEvent, { capture });
if (detectTouch) {
target.removeEventListener(touchEventType, handleTouchEvent, {
capture,
});
}
};
}, [enabled, capture, eventType, touchEventType, detectTouch, eventTarget]);
}
|