1.0.5 • Published 2 years ago

@utilityjs/use-on-outside-click v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

A React hook that invokes a callback when user clicks outside of the target element.

license npm latest package npm downloads types

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.