mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
More DRY code. Also move non-hooks to separate directories. BREAKING CHANGE: all `create*` factories been moved to `factory` subdirectory and in case direct import should be imported like `react-use/esm/factory/createBreakpoint` BREAKING CHANGE: `comps` directory renamed to `component`
32 lines
858 B
TypeScript
32 lines
858 B
TypeScript
import { RefObject, useEffect, useRef } from 'react';
|
|
import { off, on } from './misc/util';
|
|
|
|
const defaultEvents = ['mousedown', 'touchstart'];
|
|
|
|
const useClickAway = <E extends Event = Event>(
|
|
ref: RefObject<HTMLElement | null>,
|
|
onClickAway: (event: E) => void,
|
|
events: string[] = defaultEvents
|
|
) => {
|
|
const savedCallback = useRef(onClickAway);
|
|
useEffect(() => {
|
|
savedCallback.current = onClickAway;
|
|
}, [onClickAway]);
|
|
useEffect(() => {
|
|
const handler = (event) => {
|
|
const { current: el } = ref;
|
|
el && !el.contains(event.target) && savedCallback.current(event);
|
|
};
|
|
for (const eventName of events) {
|
|
on(document, eventName, handler);
|
|
}
|
|
return () => {
|
|
for (const eventName of events) {
|
|
off(document, eventName, handler);
|
|
}
|
|
};
|
|
}, [events, ref]);
|
|
};
|
|
|
|
export default useClickAway;
|