@utilityjs/use-on-outside-click
TypeScript icon, indicating that this package has built-in type declarations

1.0.5 • Public • Published

useOnOutsideClick

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.

Package Sidebar

Install

npm i @utilityjs/use-on-outside-click

Weekly Downloads

8

Version

1.0.5

License

MIT

Unpacked Size

5.61 kB

Total Files

8

Last publish

Collaborators

  • mimshins