Hooks.tsx39 lines · main
| 1 | 'use client' |
| 2 | |
| 3 | import { useEffect } from 'react' |
| 4 | |
| 5 | /* |
| 6 | reference https://usehooks.com/useOnClickOutside/ |
| 7 | */ |
| 8 | |
| 9 | function useOnClickOutside(ref: any, handler: Function) { |
| 10 | useEffect( |
| 11 | () => { |
| 12 | const listener = (event: Event) => { |
| 13 | // Do nothing if clicking ref's element or descendent elements |
| 14 | if (!ref.current || ref.current.contains(event.target)) { |
| 15 | return |
| 16 | } |
| 17 | |
| 18 | handler(event) |
| 19 | } |
| 20 | |
| 21 | document.addEventListener('mousedown', listener) |
| 22 | document.addEventListener('touchstart', listener) |
| 23 | |
| 24 | return () => { |
| 25 | document.removeEventListener('mousedown', listener) |
| 26 | document.removeEventListener('touchstart', listener) |
| 27 | } |
| 28 | }, |
| 29 | // Add ref and handler to effect dependencies |
| 30 | // It's worth noting that because passed in handler is a new ... |
| 31 | // ... function on every render that will cause this effect ... |
| 32 | // ... callback/cleanup to run every render. It's not a big deal ... |
| 33 | // ... but to optimize you can wrap handler in useCallback before ... |
| 34 | // ... passing it into this hook. |
| 35 | [ref, handler] |
| 36 | ) |
| 37 | } |
| 38 | |
| 39 | export { useOnClickOutside } |