JAVASCRIPT

Detect Clicks Outside an Element with useClickOutside React Hook

Build a `useClickOutside` React hook to detect when a user clicks anywhere outside a specific DOM element, ideal for closing modals, dropdowns, or popovers.

import { useEffect, useRef } from 'react';

function useClickOutside(handler) {
  const ref = useRef(null);

  useEffect(() => {
    const listener = (event) => {
      // Do nothing if clicking ref's element or descendant elements
      if (!ref.current || ref.current.contains(event.target)) {
        return;
      }
      handler(event);
    };

    document.addEventListener('mousedown', listener);
    document.addEventListener('touchstart', listener);

    return () => {
      document.removeEventListener('mousedown', listener);
      document.removeEventListener('touchstart', listener);
    };
  }, [ref, handler]); // Only re-run if ref or handler changes

  return ref;
}

// Example Usage:
// function DropdownMenu() {
//   const [isOpen, setIsOpen] = useState(false);
//   const dropdownRef = useClickOutside(() => setIsOpen(false));

//   return (
//     <div ref={dropdownRef} style={{ border: '1px solid black', padding: '10px' }}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{ background: 'lightgray', padding: '5px', marginTop: '5px' }}>
//           <p>Dropdown Item 1</p>
//           <p>Dropdown Item 2</p>
//         </div>
//       )}
//     </div>
//   );
// }
How it works: The `useClickOutside` hook provides a way to detect clicks that occur outside a referenced DOM element. It takes a `handler` function as an argument, which is executed whenever an outside click is detected. The hook utilizes `useRef` to create a mutable reference to the target element and `useEffect` to attach global `mousedown` and `touchstart` event listeners to the document. These listeners check if the clicked target is outside the referenced element, invoking the handler if it is. This is incredibly useful for closing modals, dropdowns, or tooltips when a user clicks away.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs