JAVASCRIPT

Detect Clicks Outside a Component

A custom React hook to detect clicks outside of a specified DOM element, perfect for closing dropdowns, modals, or tooltips when users click elsewhere.

import { useRef, useEffect } from 'react';

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

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

    document.addEventListener('mousedown', maybeHandler);

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

  return domNode;
}

// Example Usage:
// import React, { useState } from 'react';
// function Dropdown() {
//   const [isOpen, setIsOpen] = useState(false);
//   const dropdownRef = useClickOutside(() => setIsOpen(false));

//   return (
//     <div ref={dropdownRef}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{ border: '1px solid black', padding: '10px', marginTop: '5px' }}>
//           Dropdown Content
//         </div>
//       )}
//     </div>
//   );
// }
How it works: This custom React hook creates a `ref` that you attach to a DOM element. It then adds a global `mousedown` event listener to the `document`. If a click occurs outside the referenced element, the provided `handler` function is called, allowing you to close a modal, dropdown, or perform other actions. It efficiently cleans up the event listener on unmount to prevent memory leaks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs