Skip to content

useOutsideClick

React hook to detect clicks outside of a specified component.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useOutsideClick
sh
npx @novajslabs/cli add useOutsideClick
sh
pnpm dlx @novajslabs/cli add useOutsideClick

Or copy and paste the code into your project:

ts
import { useEffect, MutableRefObject } from "react";

export const useOutsideClick = (
  ref: MutableRefObject<HTMLElement | null>,
  fn: () => void
) => {
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        fn();
      }
    };

    document.addEventListener("click", handleClickOutside);

    return () => {
      document.removeEventListener("click", handleClickOutside);
    };
  }, [ref, fn]);
};
js
import { useEffect } from "react";

export const useOutsideClick = (ref, fn) => {
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (ref.current && !ref.current.contains(event.target)) {
        fn();
      }
    };

    document.addEventListener("click", handleClickOutside);
    return () => {
      document.removeEventListener("click", handleClickOutside);
    };
  }, [ref, fn]);
};

Requirements

React 16.8 or higher

Parameters

ref required

  • Type: HTMLElement | null

The DOM element to detect clicks outside of.

fn required

  • Type: function

A callback function to execute when a click outside the referenced element is detected.

Example

tsx
import { useState, useRef } from "react";
import { useOutsideClick } from "./hooks/useOutsideClick";

const DropdownMenu = () => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const toggleMenu = () => {
    setIsOpen(!isOpen);
  };

  const closeMenu = () => {
    setIsOpen(false);
  };

  useOutsideClick(dropdownRef, closeMenu);

  return (
    <div ref={dropdownRef}>
      <button onClick={toggleMenu}>Toggle Dropdown</button>
      {isOpen && (
        <div>
          <ul>
            <li>Option 1</li>
            <li>Option 2</li>
            <li>Option 3</li>
          </ul>
        </div>
      )}
    </div>
  );
};

export default DropdownMenu;

Use cases

Here are some use cases where this React hook is useful:

  • Closing dropdown menus when clicking outside
  • Dismissing modal dialogs when clicking outside
  • Hiding context menus on outside click