Install

npm
npm i use-any-hook

Description

The useClickOutside hook allows you to detect clicks outside a specific DOM element and execute a callback function in response. This is useful for closing modal dialogs, dropdown menus, or resetting states when the user interacts outside of a specified UI component boundary.

Parameters

NameTypeDescription
refRefObjectA ref object pointing to the DOM element you want to monitor.
callbackFunctionThe function to call when a click is detected outside the specified ref.

Return Values

NameTypeDescription
NoneN/AThis hook does not return any values.

Example

useClickOutside.example.tsx
import { useRef } from "react";
import { useClickOutside } from "use-any-hook";

function MyComponent() {
  const myRef = useRef < HTMLDivElement > null;

  const handleClickOutside = () => {
    console.log("Clicked outside the element");
  };

  useClickOutside(myRef, handleClickOutside);

  return (
    <div className="p-14 bg-red-500" ref={myRef}>
      {/* Your content here */}
    </div>
  );
}