mirror of
https://github.com/placeholder-soft/web.git
synced 2026-01-12 17:02:57 +08:00
* Deprecation content * checkpoint, considering factoring out nav * Update FAQ * Configure code sharing ; nav * Disable SSR to avoid hydration errors * Add comment * Lint * Update FAQ * Deprecate every page
24 lines
619 B
TypeScript
24 lines
619 B
TypeScript
import { useEffect, useRef } from 'react';
|
|
|
|
function useClickAway<T extends HTMLElement>(handler: (event: MouseEvent) => void) {
|
|
const ref = useRef<T>(null);
|
|
|
|
useEffect(() => {
|
|
const listener = (event: MouseEvent) => {
|
|
// Do nothing if clicking ref element or descendent elements
|
|
if (!ref.current || ref.current.contains(event.target as Node)) {
|
|
return;
|
|
}
|
|
handler(event);
|
|
};
|
|
document.addEventListener('click', listener);
|
|
return () => {
|
|
document.removeEventListener('click', listener);
|
|
};
|
|
}, [ref, handler]);
|
|
|
|
return ref;
|
|
}
|
|
|
|
export default useClickAway;
|