JAVASCRIPT

Detecting Clicks Outside a Component with useOutsideClick

Implement interactive elements like dropdowns or modals that close when clicked outside, using a custom `useOutsideClick` React hook for better UX.

import { useEffect } from 'react';

function useOutsideClick(ref, handler) {
  useEffect(() => {
    const listener = (event) => {
      // Do nothing if clicking ref's element or descendent 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]);
}
How it works: This hook simplifies detecting clicks that occur outside a specified DOM element. It takes a `ref` to the target element and a `handler` function. When a 'mousedown' or 'touchstart' event occurs outside the referenced element, the `handler` is executed, commonly used for closing modals, dropdowns, or popovers, enhancing user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs