@itgold/grandbazar-ui-kit
Version:
Grandbazar.io UI component library: React, Typescript, Tailwind, Rollup, Storybook, Jest.
17 lines (14 loc) • 488 B
text/typescript
import { useEffect, RefObject } from 'react';
export function useClickOutside(ref: RefObject<HTMLElement>, callback: () => void) {
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) {
callback();
}
};
window.addEventListener('mousedown', handleClickOutside);
return () => {
window.removeEventListener('mousedown', handleClickOutside);
};
}, [ref, callback]);
}