@utilityjs/use-on-outside-click
v1.0.5
Published
A React hook that invokes a callback when user clicks outside of the target element.
Downloads
455
Maintainers
Readme
A React hook that invokes a callback when user clicks outside of the target element.
npm i @utilityjs/use-on-outside-click | yarn add @utilityjs/use-on-outside-click
Usage
const MyComponent = (props) => {
const targetRef = React.useRef<HTMLDivElement>();
useOnOutsideClick(targetRef, () => {
console.log("OUTSIDE!");
});
useOnOutsideClick(targetRef, () => {
console.log("OUTSIDE AND NOT #some-id!");
// Extending the condition
}, event => ((event.target) as Node).id !== "some-id");
return (
<React.Fragment>
<div ref={targetRef}>...</div>
</React.Fragment>
);
};
API
useOnOutsideClick(target, callback, extendCondition?)
declare const useOnOutsideClick: <T extends HTMLElement = HTMLElement>(
target: T | React.RefObject<T> | null,
callback: (event: MouseEvent) => void,
extendCondition?: (event: MouseEvent) => boolean
) => void;
target
The target to test the conditions against.
callback
The callback that is called when the conditions are met.
extendCondition
The function that extends the test conditions.