Skip to content

Commit

Permalink
feat: fix ref useOutsideClick
Browse files Browse the repository at this point in the history
  • Loading branch information
NikitaCG committed Sep 15, 2023
1 parent 672226f commit 7b009f2
Showing 1 changed file with 12 additions and 16 deletions.
28 changes: 12 additions & 16 deletions src/components/utils/useOutsideClick/useOutsideClick.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,20 @@ type UseOutsideClickType = <K extends HTMLElement>(props: UseOutsideClickProps<K
*/
export const useOutsideClick: UseOutsideClickType = ({ref, handler}) => {
React.useEffect(() => {
if (ref) {
const callback = (e: MouseEvent | TouchEvent) => {
const elem = ref?.current;
const callback = (e: MouseEvent | TouchEvent) => {
const elem = ref?.current;

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

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

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

return undefined;
return () => {
window.removeEventListener('click', callback, {capture: true});
window.removeEventListener('touchstart', callback, {capture: true});
};
}, [handler, ref]);
};

0 comments on commit 7b009f2

Please sign in to comment.