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, RefObject } from "react";
export const useOutsideClick = (
ref: RefObject<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:
RefObject<HTMLElement | null>
The DOM element to detect clicks outside of.
fn required
- Type:
() => void
A callback function to execute when a click outside the referenced element is detected.