1// https://usehooks-ts.com/react-hook/use-on-click-outside
2import { RefObject, useEffect } from 'react';
4type AnyEvent = MouseEvent | TouchEvent;
6function useOnClickOutside<T extends HTMLElement = HTMLElement>(
8 handler: (event: AnyEvent) => void
11 const listener = (event: AnyEvent) => {
12 const el = ref?.current;
14 // Do nothing if clicking ref's element or descendent elements
15 if (!el || el.contains(event.target as Node)) {
22 document.addEventListener(`mousedown`, listener);
23 document.addEventListener(`touchstart`, listener);
26 document.removeEventListener(`mousedown`, listener);
27 document.removeEventListener(`touchstart`, listener);
30 // Reload only if ref or handler changes
34export default useOnClickOutside;
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list