JAVASCRIPT

Detect Clicks Outside a Component with React's useOutsideClick Hook

Create a useOutsideClick custom hook in React to close modals, dropdowns, or dismiss elements when a user clicks anywhere outside the specified component.

import { useEffect, useRef } from 'react';

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

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (ref.current && !ref.current.contains(event.target)) {
        handler(event);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [handler]);

  return ref;
}

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

//   return (
//     <div ref={dropdownRef}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{ border: '1px solid black', padding: '10px' }}>
//           <p>Dropdown Content</p>
//           <button>Item 1</button>
//           <button>Item 2</button>
//         </div>
//       )}
//     </div>
//   );
// }
How it works: The `useOutsideClick` hook provides a mechanism to detect clicks that occur outside of a referenced DOM element. It uses `useRef` to create a mutable reference that can be attached to any component. A `useEffect` hook adds a global `mousedown` event listener to the `document`. When a click occurs, it checks if the clicked target is *not* contained within the referenced element, and if so, it invokes the provided `handler` function. This is perfect for closing modals, dropdowns, or tooltips.

Need help integrating this into your project?

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

Hire DigitalCodeLabs