fix: 🐛 support click away on iOS, allow user to chose events

This commit is contained in:
streamich 2019-04-23 16:34:05 +02:00
parent 56a868dc3a
commit f14e1d77d2

View File

@ -1,15 +1,25 @@
import { RefObject, useEffect } from 'react';
import { off, on } from './util';
const useClickAway = (ref: RefObject<HTMLElement | null>, onClickAway: (event: KeyboardEvent) => void) => {
const defaultEvents = ['mousedown', 'touchstart'];
const useClickAway = (
ref: RefObject<HTMLElement | null>,
onClickAway: (event: KeyboardEvent) => void,
events: string[] = defaultEvents
) => {
useEffect(() => {
const handler = event => {
const { current: el } = ref;
el && !el.contains(event.target) && onClickAway(event);
};
on(document, 'click', handler);
for (const eventName of events) {
on(document, eventName, handler);
}
return () => {
off(document, 'click', handler);
for (const eventName of events) {
off(document, eventName, handler);
}
};
});
};