generated from abelflopes/lerna-monorepo-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9d94454
commit 738a2aa
Showing
2 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters