use-on-click-outside.ts 575 B

12345678910111213141516171819
  1. import { RefObject } from 'react';
  2. import useEventListener from './use-event-listener';
  3. type Handler = (event: MouseEvent) => void;
  4. const useOnClickOutside = <T extends HTMLElement = HTMLElement>(ref: RefObject<T>, handler: Handler, mouseEvent: 'mousedown' | 'mouseup' = 'mousedown'): void => {
  5. useEventListener(mouseEvent, (event) => {
  6. const el = ref?.current;
  7. // Do nothing if clicking ref's element or descendent elements
  8. if (!el || el.contains(event.target as Node)) {
  9. return;
  10. }
  11. handler(event);
  12. });
  13. };
  14. export default useOnClickOutside;