mirror of
https://github.com/streamich/react-use.git
synced 2026-01-25 14:17:16 +00:00
This re-implements outside click hook functionality from scratch,
removes dependency on use-onoutsideclick package.
BREAKING CHANGE: 🧨 useOutsideClick is now useClickAway
18 lines
455 B
TypeScript
18 lines
455 B
TypeScript
import {RefObject, useEffect} from 'react';
|
|
import {on, off} from './util';
|
|
|
|
const useClickAway = (ref: RefObject<HTMLElement | null>, onClickAway: () => void) => {
|
|
useEffect(() => {
|
|
const handler = (event) => {
|
|
const {current: el} = ref;
|
|
el && !el.contains(event.target) && onClickAway();
|
|
};
|
|
on(document, 'click', handler);
|
|
return () => {
|
|
off(document, 'click', handler);
|
|
};
|
|
});
|
|
};
|
|
|
|
export default useClickAway;
|