JAVASCRIPT

Handling Clicks Outside with useOnClickOutside

Implement a reusable React hook `useOnClickOutside` to detect clicks that occur outside a specified component, perfect for closing modals, dropdowns, or sidebars.

import { useEffect, useRef } from 'react';

const useOnClickOutside = (ref, handler) => {
  useEffect(() => {
    const listener = (event) => {
      // Do nothing if clicking ref's element or descendant 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]); // Only re-run if ref or handler changes
};

export default useOnClickOutside;

// Example Usage:
// function DropdownMenu() {
//   const [isOpen, setIsOpen] = useState(false);
//   const dropdownRef = useRef(null);
//
//   useOnClickOutside(dropdownRef, () => setIsOpen(false));
//
//   return (
//     <div ref={dropdownRef} style={{ position: 'relative', display: 'inline-block' }}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{
//           position: 'absolute',
//           border: '1px solid gray',
//           padding: '10px',
//           backgroundColor: 'white',
//           minWidth: '150px'
//         }}>
//           <div>Item 1</div>
//           <div>Item 2</div>
//         </div>
//       )}
//     </div>
//   );
// }
How it works: The `useOnClickOutside` hook facilitates closing UI elements like dropdowns or modals when a user clicks anywhere outside of them. It attaches event listeners to the `document` for `mousedown` and `touchstart` events. When an event occurs, it checks if the click target is outside the provided `ref`'s element. If so, it invokes the specified `handler` function, typically used to update the component's state (e.g., setting `isOpen` to `false`).

Need help integrating this into your project?

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

Hire DigitalCodeLabs