JAVASCRIPT

React `useClickOutside` Hook for Closing Modals/Dropdowns

A custom React hook to detect clicks outside a specific DOM element, useful for closing modals, dropdowns, or popovers when a user clicks away.

import { useEffect, useRef } from 'react';

const useClickOutside = (handler) => {
  const domNode = useRef();

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

    document.addEventListener('mousedown', maybeHandler);

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

  return domNode;
};

export default useClickOutside;

/* Example Usage:
import React, { useState } from 'react';

function MyComponent() {
  const [isOpen, setIsOpen] = useState(false);
  const ref = useClickOutside(() => setIsOpen(false));

  return (
    <div ref={ref} style={{ border: '1px solid black', padding: '20px' }}>
      <button onClick={() => setIsOpen(!isOpen)}>
        Toggle Dropdown
      </button>
      {isOpen && (
        <div style={{ background: 'lightgray', padding: '10px', marginTop: '10px' }}>
          Dropdown Content
        </div>
      )}
    </div>
  );
}
*/
How it works: This hook leverages `useEffect` and `useRef` to attach a global `mousedown` event listener to the document. It checks if the clicked target is outside the referenced `domNode`. If so, it calls the provided `handler` function, typically used to close a modal or dropdown. The event listener is cleaned up 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