JAVASCRIPT

React Hook: useClickOutside for Modals and Dropdowns

A custom React hook, `useClickOutside`, detects clicks outside a specified DOM element, useful for closing modals, dropdowns, or popovers when users click away.

import { useEffect, useRef } from 'react';

function useClickOutside(handler) {
  const domNodeRef = useRef();

  useEffect(() => {
    const maybeHandler = (event) => {
      if (!domNodeRef.current.contains(event.target)) {
        handler();
      }
    };

    document.addEventListener('mousedown', maybeHandler);

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

  return domNodeRef;
}

// How to use it:
/*
function MyComponent() {
  const [isOpen, setIsOpen] = useState(false);
  const clickOutsideRef = useClickOutside(() => setIsOpen(false));

  return (
    <div ref={clickOutsideRef} style={{ border: '1px solid black', padding: '20px' }}>
      <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
      {isOpen && (
        <div style={{ background: 'lightgray', padding: '10px', marginTop: '10px' }}>
          This is a dropdown content.
        </div>
      )}
    </div>
  );
}
*/
How it works: The `useClickOutside` hook creates a `useRef` to attach to a DOM element. It then sets up an effect that adds a 'mousedown' event listener to the entire document. When a click occurs, it checks if the clicked target is *inside* the referenced element. If it's not, the provided `handler` function is called, typically to close a modal or dropdown. The effect cleans up the event listener when the component unmounts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs