<!-- .github/pull_request_template.md --> ## Description <!-- Provide a clear description of the changes in this PR --> ## DCO Affirmation I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin. --------- Co-authored-by: Daulet Amirkhanov <damirkhanov01@gmail.com>
25 lines
729 B
TypeScript
25 lines
729 B
TypeScript
import { useEffect, useRef } from "react";
|
|
|
|
export default function useOutsideClick<ElementType extends HTMLElement>(callbackFn: () => void, isEnabled = true) {
|
|
const rootElementRef = useRef<ElementType>(null);
|
|
|
|
useEffect(() => {
|
|
function handleClickOutside(event: MouseEvent) {
|
|
const clickedElement = event.target;
|
|
|
|
if (clickedElement && rootElementRef.current && !rootElementRef.current?.contains(clickedElement as Node)) {
|
|
callbackFn();
|
|
}
|
|
}
|
|
|
|
if (isEnabled) {
|
|
document.addEventListener("click", handleClickOutside);
|
|
|
|
return () => {
|
|
document.removeEventListener("click", handleClickOutside);
|
|
};
|
|
}
|
|
}, [callbackFn, isEnabled]);
|
|
|
|
return rootElementRef;
|
|
}
|