JAVASCRIPT

How to detect clicks outside an element with useClickOutside hook

Implement a custom React useClickOutside hook to easily close dropdowns, modals, or menus when users click anywhere outside a specified DOM element.

import { useEffect, useRef } from 'react';

function useClickOutside(ref, handler) {
  useEffect(() => {
    const listener = (event) => {
      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]);
}

// Example Usage:
// function Dropdown() {
//   const [isOpen, setIsOpen] = useState(false);
//   const dropdownRef = useRef(null);
//
//   useClickOutside(dropdownRef, () => setIsOpen(false));
//
//   return (
//     <div ref={dropdownRef}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{ border: '1px solid black', padding: '10px' }}>
//           Dropdown content
//         </div>
//       )}
//     </div>
//   );
// }
How it works: The useClickOutside hook attaches global event listeners for 'mousedown' and 'touchstart'. When an event occurs, it checks if the click was outside the referenced element. If so, it invokes the provided handler function, which is commonly used to close UI components like dropdowns, modals, or sidebars.

Need help integrating this into your project?

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

Hire DigitalCodeLabs