HooksuseOnClickOutside

useOnClickOutside()

The useOnClickOutside() hook allows you to detect click or touch events that happen outside of a specified DOM element. It is essential for implementing behaviors like closing a modal when clicking the backdrop or hiding a dropdown menu when clicking away.

Import

typescript
import { useOnClickOutside } from 'the-react-hooks';

Usage

Open the card, then click anywhere outside of it to close.

State: CLOSED
Component.tsx
import { useOnClickOutside } from 'the-react-hooks';
import { useRef, useState } from 'react';

export const Component = () => {
  const [isOpen, setIsOpen] = useState(false);
  const ref = useRef(null);

  useOnClickOutside(ref, () => setIsOpen(false));

  return (
    <div>
      <button onClick={() => setIsOpen(true)}>Open</button>

      {isOpen && (
        <div ref={ref}>
          This is the dropdown content.
          Click outside to close me.
        </div>
      )}
    </div>
  );
}

API

Arguments

  • ref RefObject<T> The React ref object attached to the element you want to detect outside clicks for.
  • handler (event) => void The function to execute when a click outside is detected.
  • mouseEvent mousedown | mouseup (Optional) The mouse event type to listen for. Defaults to "mousedown".
  • touchEvent touchstart | touchend (Optional) The touch event type to listen for. Defaults to touchstart".

Returns

This hook returns void.