mirror of
https://github.com/streamich/react-use.git
synced 2026-01-25 14:17:16 +00:00
feat: improve useClickAway() hook (#394)
This commit is contained in:
commit
c60df19ebc
@ -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 (
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user