Skip to content

Commit

Permalink
feat: create useOnClickOutside hook
Browse files Browse the repository at this point in the history
  • Loading branch information
NikitaCG committed Sep 13, 2023
1 parent 1a602ec commit e1d2192
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
Empty file.
36 changes: 36 additions & 0 deletions src/components/utils/useOnClickOutside/useOnClickOutside.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React from 'react';

export type UseOnClickOutsideType = <T extends HTMLElement>({
observedRef,
enabled,
}: {
observedRef: React.RefObject<T>;
enabled?: boolean;
handleCallback?: () => void;
}) => void;

export const useOnClickOutside: UseOnClickOutsideType = ({
observedRef,
enabled = true,
handleCallback,
}) => {
React.useEffect(() => {
if (enabled && observedRef) {
const handler = (e: MouseEvent) => {
const elem = observedRef?.current;

if (elem && !elem.contains(e.target as Node) && handleCallback) {
handleCallback();
}
};

window.addEventListener('click', handler, {capture: true});

return () => {
window.removeEventListener('click', handler, {capture: true});
};
}

return undefined;
}, [enabled, handleCallback, observedRef]);
};

0 comments on commit e1d2192

Please sign in to comment.