React.js utilities to listen for click away events.
Utilities contain a hook and a high order click away component.
# via npm
npm install @donnikitos/react-clickaway
# via yarn
yarn add @donnikitos/react-clickaway
The useClickAwayListener
hook takes 2 to 3 arguments, which register the click-away-listener.
The hook does not return any value, it just sits the in the code.
function useClickAwayListener(
observedElement: Element | null | undefined,
callBack: (event: MouseEvent) => void,
excludedElements?: (Element | null | undefined)[],
): void;
import { useState } from 'react';
import { useClickAwayListener } from 'react-clickawaylistener';
// use in Component
function App(props) {
const [reference, setReference] = useState<HTMLElement | null>(null);
const [excluded, setExcluded] = useState<HTMLElement | null>(null);
const cb = useCallback(() => {
console.log('Event triggered!');
}, []);
useClickAwayListener(reference, cb, [excluded]);
return (
<>
<div>I trigger the click-away-event</div>
<div ref={setReference}>I do not trigger the event</div>
<div>I trigger it too</div>
<div ref={excluded}>I am not</div>
</>
);
}
MIT Copyright (c) 2021 Nikita 'donnikitos' Nitichevski.