Skip to content

Commit

Permalink
feat: improve useClickAway() hook (#394)
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich authored Jun 19, 2019
2 parents d2be349 + 8fb5895 commit c60df19
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 7 deletions.
2 changes: 1 addition & 1 deletion docs/useClickAway.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
5 changes: 2 additions & 3 deletions src/__stories__/useClickAway.story.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { action } from '@storybook/addon-actions';
import { storiesOf } from '@storybook/react';
import * as React from 'react';
import { useRef } from 'react';
Expand All @@ -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
Expand Down
10 changes: 7 additions & 3 deletions src/useClickAway.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RefObject, useEffect } from 'react';
import { RefObject, useEffect, useRef } from 'react';
import { off, on } from './util';

const defaultEvents = ['mousedown', 'touchstart'];
Expand All @@ -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);
Expand All @@ -21,7 +25,7 @@ const useClickAway = (
off(document, eventName, handler);
}
};
});
}, [events, ref]);
};

export default useClickAway;

0 comments on commit c60df19

Please sign in to comment.