JAVASCRIPT

React `useOnClickOutside` Hook for Closing Elements

Create a reusable React `useOnClickOutside` hook to detect clicks outside a specified DOM element, enabling easy implementation of closing logic for modals, dropdowns, and context menus.

import { useEffect } from 'react';

function useOnClickOutside(ref, handler) {
  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

}

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

//   return (
//     <div ref={ref}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{ border: '1px solid gray', padding: '10px' }}>
//           <p>Item 1</p>
//           <p>Item 2</p>
//         </div>
//       )}
//     </div>
//   );
// }
How it works: The `useOnClickOutside` hook provides a way to trigger a function when a user clicks outside a referenced DOM element. This is incredibly useful for UI components like modals, dropdowns, or popovers, allowing them to close automatically when the user interacts with the rest of the page. It attaches and cleans up event listeners for mouse and touch events.

Need help integrating this into your project?

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

Hire DigitalCodeLabs