JAVASCRIPT

Detect Clicks Outside a React Component with `useOutsideClick`

Build a custom `useOutsideClick` React hook to close modals, dropdowns, or dismiss elements when a user clicks anywhere outside a referenced component.

import { useEffect, useRef } from 'react';

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

  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);
    };
  }, [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' }}>
//           Dropdown Content
//         </div>
//       )}
//     </div>
//   );
// }
How it works: This `useOutsideClick` hook provides a robust way to detect when a user clicks outside a specified React component. It attaches event listeners to the document and calls a provided handler function if the click target is not within the component's reference. This is crucial for UI patterns like closing dropdowns, modals, or popovers when users interact elsewhere on the page.

Need help integrating this into your project?

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

Hire DigitalCodeLabs