use-on-outside-click
Version:
A lightweight and flexible React hook to detect clicks outside one or multiple elements.
22 lines (21 loc) • 707 B
JavaScript
import { useRef as f, useEffect as m } from "react";
function g(t, n, { skip: c = !1 } = {}) {
const u = f(n), r = f(t);
u.current = n, r.current = t;
const s = (e) => e ? typeof e == "string" ? document.querySelector(e) : "current" in e ? e.current : e : null;
m(() => {
if (c) return;
const e = (l) => {
const o = l.target;
if (!o) return;
const i = (Array.isArray(r.current) ? r.current.map(s) : [s(r.current)]).filter(Boolean), a = i.some((d) => d.contains(o));
i.length && !a && u.current();
};
return document.addEventListener("click", e), () => {
document.removeEventListener("click", e);
};
}, [c]);
}
export {
g as useOnOutsideClick
};