JavaScript Development Space

Handle Outside Clicks in React with TypeScript

Detecting a click outside of a React component is a common requirement, especially when dealing with dropdowns, modals, or tooltips that should close when a user clicks outside of them.

useOutsideClick hook

ts
1 import { RefObject, useEffect, useRef } from 'react';
2
3 const events = [`mousedown`, `touchstart`, `mouseup`, `touchend`];
4
5 type useClickOutsideProps = {
6 ref: RefObject<HTMLElement | undefined>;
7 callback: () => void;
8 };
9
10 export const useOutsideClick = ({ ref, callback }: useOutsideClickProps) => {
11 useEffect(() => {
12 const handleClickOutside = (event: MouseEvent | TouchEvent) => {
13 if (ref.current && !ref.current.contains(event.target as Node)) {
14 callback();
15 }
16 };
17
18 for (const event of events) {
19 document.addEventListener(event, handleClickOutside);
20 }
21
22 return () => {
23 for (const event of events) {
24 document.removeEventListener(event, handleClickOutside);
25 }
26 };
27 }, [callback]);
28 };
JavaScript Development Space

© 2024 JavaScript Development Space - Master JS and NodeJS. All rights reserved.