Skip to main content

useOnClickOutside Hook

useOnClickOutside is a custom React hook designed to detect and handle clicks outside a specified DOM element. It's useful for implementing behaviors like closing a modal or dropdown menu when the user clicks outside of it.

Features

  • Detects clicks outside a specified element.
  • Executes a callback function when an outside click is detected.
  • Listens for multiple event types: mousedown, touchstart, and PointerEvent.

Parameters

ParameterTypeDescription
refanyRef object targeting the element to monitor.
handleranyCallback function to execute on an outside click.

Implementation

import { useEffect } from "react";

export const useOnClickOutside = (ref, handler) => {
useEffect(() => {
const listener = (event) => {
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener("mousedown", listener);
document.addEventListener("touchstart", listener);
document.addEventListener("PointerEvent", listener);
return () => {
document.removeEventListener("mousedown", listener);
document.removeEventListener("touchstart", listener);
document.removeEventListener("PointerEvent", listener);
};
}, [ref]);
};

Usage

  1. Attach the hook to a component by passing a reference (ref) to the element and a callback (handler) function.
  2. The hook listens for clicks outside the referenced element and executes the handler when such a click occurs.

Example:

const MyComponent = () => {
const ref = useRef();
const handler = () => console.log("Clicked outside");

useOnClickOutside(ref, handler);

return <div ref={ref}>My Component</div>;
};

Notes

  • Ensure the element you want to monitor is referenced using useRef.
  • To optimize performance, wrap the handler function in useCallback before passing it to the hook, especially if the handler is defined within a component that re-renders frequently.

This documentation provides an overview of the useOnClickOutside hook, explaining its purpose, parameters, and usage. Adjust the implementation details as per your specific project requirements.