JAVASCRIPT

Detect Clicks Outside a Component with useClickOutside Hook

Create a custom React hook, useClickOutside, to easily detect clicks that occur outside a specified DOM element, perfect for closing modals and dropdowns.

import { useEffect, useRef } from 'react';

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

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

    document.addEventListener('mousedown', maybeHandler);

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

  return domNodeRef;
}

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

  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
      {isOpen && (
        <div
          ref={menuRef}
          style={{
            position: 'absolute',
            border: '1px solid #ccc',
            padding: '10px',
            background: '#fff',
            minWidth: '150px'
          }}
        >
          <p>Item 1</p>
          <p>Item 2</p>
        </div>
      )}
    </div>
  );
}
export default DropdownMenu;
*/

export default useClickOutside;
How it works: The useClickOutside is a custom hook that allows you to execute a function when a click event occurs outside of a referenced DOM element. It utilizes useRef to create a reference to the target element and useEffect to attach and clean up a global 'mousedown' event listener. This hook is commonly used for closing modals, dropdowns, or popovers when the user clicks elsewhere on the page. The commented example illustrates its practical application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs