Skip to content

Commit

Permalink
feat: add click outside util
Browse files Browse the repository at this point in the history
  • Loading branch information
abelflopes committed Jul 4, 2024
1 parent 9d94454 commit 738a2aa
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
35 changes: 35 additions & 0 deletions packages/utils/react/src/click-outside.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { type default as React, useCallback, useEffect } from "react";

export const useOnClickOutside = <T extends Array<React.RefObject<HTMLElement>>>(
active: boolean,
refs: T,
onClickOutside: () => void,
): void => {
const clickHandler = useCallback(
(e: MouseEvent) => {
const { target } = e;

if (!active) return;
else if (!(target instanceof HTMLElement))
throw new Error("click outside target is not an HTMLElement");
else if (!refs.every((i) => Boolean(i)))
throw new Error("some click outside ref is not available");
else if (refs.some((i) => i.current?.contains(target))) return;

onClickOutside();
},
[active, onClickOutside, refs],
);

useEffect(() => {
if (!active) return;

const container = document.documentElement;

container.addEventListener("click", clickHandler);

return (): void => {
container.removeEventListener("click", clickHandler);
};
}, [active, clickHandler]);
};
2 changes: 2 additions & 0 deletions packages/utils/react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ export * from "./display-name";
export * from "./polimorphy";

export * from "./component-to-text";

export * from "./click-outside";

0 comments on commit 738a2aa

Please sign in to comment.