feat: improve useClickAway() hook (#394)

This commit is contained in:
Vadim Dalecky 2019-06-19 15:10:44 +02:00 committed by GitHub
commit c60df19ebc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 10 additions and 7 deletions

View File

@ -12,7 +12,7 @@ import {useClickAway} from 'react-use';
const Demo = () => {
const ref = useRef(null);
useClickAway(ref, () => {
alert('OUTSIDE CLICKED');
console.log('OUTSIDE CLICKED');
});
return (

View File

@ -1,3 +1,4 @@
import { action } from '@storybook/addon-actions';
import { storiesOf } from '@storybook/react';
import * as React from 'react';
import { useRef } from 'react';
@ -6,9 +7,7 @@ import ShowDocs from './util/ShowDocs';
const Demo = () => {
const ref = useRef(null);
useClickAway(ref, () => {
alert('OUTSIDE CLICKED');
});
useClickAway(ref, action('outside clicked'));
return (
<div

View File

@ -1,4 +1,4 @@
import { RefObject, useEffect } from 'react';
import { RefObject, useEffect, useRef } from 'react';
import { off, on } from './util';
const defaultEvents = ['mousedown', 'touchstart'];
@ -8,10 +8,14 @@ const useClickAway = (
onClickAway: (event: KeyboardEvent) => 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) && onClickAway(event);
el && !el.contains(event.target) && savedCallback.current(event);
};
for (const eventName of events) {
on(document, eventName, handler);
@ -21,7 +25,7 @@ const useClickAway = (
off(document, eventName, handler);
}
};
});
}, [events, ref]);
};
export default useClickAway;