Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-cool-onclickoutside

Package Overview
Dependencies
Maintainers
1
Versions
57
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-cool-onclickoutside

React hook to listen for clicks outside of the component(s).

  • 1.7.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
63K
increased by3.76%
Maintainers
1
Weekly downloads
 
Created
Source

REACT COOL ONCLICKOUTSIDE

This is a React hook to trigger callback when user clicks outside of the target component(s) area. It's a useful logic for UI interaction design (IxD) like dismiss a dropdown menu, modal or tooltip etc. You can check the features section to learn more.

⚡️ Live demo: https://react-cool-onclickoutside.netlify.app

❤️ it? ⭐️ it on GitHub or Tweet about it.

build status coverage status npm version npm downloads npm downloads gzip size All Contributors PRs welcome Twitter URL

Features

  • 🎣 Listens for clicks outside based on React hook.
  • 👯‍♀️ Supports multiple refs to cover more use cases.
  • 🧻 Uses passive event listeners to improve scrolling performance.
  • ⛔ Scrollbar can be excluded from the callback of outside clicks.
  • 🙈 Ignores certain elements during the event loop.
  • 🙉 Enables you to stop listening for outside clicks when needed.
  • 🪟 Detects iframe clicks for better DX.
  • 🔩 Supports custom refs for some reasons.
  • 📜 Supports TypeScript type definition.
  • 🗄️ Server-side rendering compatibility.
  • 🦔 Tiny size (< 1kB gzipped). No external dependencies, aside for the react.

Requirement

To use react-cool-onclickoutside, you must use react@16.8.0 or greater which includes hooks.

Installation

This package is distributed via npm.

$ yarn add react-cool-onclickoutside
# or
$ npm install --save react-cool-onclickoutside

Usage

Common use case.

import { useState } from "react";
import useOnclickOutside from "react-cool-onclickoutside";

const Dropdown = () => {
  const [openMenu, setOpenMenu] = useState(false);
  const ref = useOnclickOutside(() => {
    setOpenMenu(false);
  });

  const handleClickBtn = () => {
    setOpenMenu(!openMenu);
  };

  return (
    <div>
      <button onClick={handleClickBtn}>Button</button>
      {openMenu && <div ref={ref}>Menu</div>}
    </div>
  );
};

Edit useOnclickOutside demo

Support multiple refs. Callback only be triggered when user clicks outside of the registered components.

import { useState } from "react";
import useOnclickOutside from "react-cool-onclickoutside";

const App = () => {
  const [showTips, setShowTips] = useState(true);
  const ref = useOnclickOutside(() => {
    setShowTips(false);
  });

  return (
    <div>
      {showTips && (
        <>
          <div ref={ref}>Tooltip 1</div>
          <div ref={ref}>Tooltip 2</div>
        </>
      )}
    </div>
  );
};

Ignore Elements by CSS Class Name

You can tell react-cool-onclickoutside to ignore certain elements during the event loop by the ignore-onclickoutside CSS class name. If you want explicit control over the class name, use the ignoreClass option.

import { useState } from "react";
import useOnclickOutside from "react-cool-onclickoutside";

// Use the default CSS class name
const App = () => {
  const ref = useOnclickOutside(() => {
    // Do something...
  });

  return (
    <div>
      <div ref={ref}>I'm a 🍕</div>
      <div>Click me will trigger the event's callback</div>
      <div className="ignore-onclickoutside">
        Click me won't trigger the event's callback
      </div>
    </div>
  );
};

// Use your own CSS class name
const App = () => {
  const ref = useOnclickOutside(
    () => {
      // Do something...
    },
    {
      ignoreClass: "my-ignore-class", // Or ["class-1", "class-2"]
    }
  );

  return (
    <div>
      <div ref={ref}>I'm a 🍕</div>
      <div>Click me will trigger the event's callback</div>
      <div className="my-ignore-class">
        Click me won't trigger the event's callback
      </div>
    </div>
  );
};

Disabling the Event Listener

In case you want to disable the event listener for performance reasons or fulfill some use cases. We provide the disabled option for you. Once you set it to true, the callback won’t be triggered.

import { useState } from "react";
import useOnclickOutside from "react-cool-onclickoutside";

const App = () => {
  const [disabled, setDisabled] = useState(false);
  const ref = useOnclickOutside(
    () => {
      // Do something...
    },
    { disabled }
  );

  const handleBtnClick = () => {
    setDisabled(true);
  };

  return (
    <div>
      <button onClick={handleBtnClick}>
        Stop listening for outside clicks
      </button>
      <div ref={ref}>I'm a 🍎</div>
    </div>
  );
};

Use Your Own ref

In case of you had a ref already or you want to share a ref for other purposes. You can pass in the ref instead of using the one provided by this hook.

const ref = useRef();

useOnclickOutside(
  () => {
    // Do something...
  },
  { refs: [ref] }
);

Detecting Iframe Clicks

Clicks on an <iframe> element won't trigger document.documentElement listeners, because it's literally different page with different security domain. However, when clicking on an iframe moves focus to its content's window that triggers the main window.blur event. react-cool-onclickoutside in conjunction the blur event with document.activeElement to detect if an iframe is clicked, and execute the provided callback.

The above-mentioned workaround has its caveats:

  • Clicks on an iframe will only trigger the provided callback once. Subsequent clicks on iframe will not trigger the callback until focus has been moved back to main window.
  • Move focus to iframe via keyboard navigation also triggers the provided callback.

For our convenience, this feature is enabled by default. You can optionally disable it by setting the detectIFrame to false if you find it conflicting with your use-case.

API

const ref = useOnclickOutside(callback: (event: Event) => void, options?: object);

You must register the ref and pass the callback to use this hook. Moreover you can access the event object via the callback's parameter, default will be MouseEvent or TouchEvent.

const callback = (event) => {
  console.log("Event: ", event);
};

The options object contains the following keys.

KeyTypeDefaultDescription
refsArrayFor some reasons, you can pass in your own ref(s) instead of using the built-in.
disabledbooleanfalseEnable/disable the event listener.
eventTypesArray['mousedown', 'touchstart']Which events to listen for.
excludeScrollbarbooleanfalseWhether or not to listen (ignore) to browser scrollbar clicks.
ignoreClassstring | string[]ignore-onclickoutsideTo ignore certain elements during the event loop by the CSS class name that you defined.
detectIFramebooleantrueTo disable the feature of detecting iframe clicks.

Articles / Blog Posts

💡 If you have written any blog post or article about react-cool-onclickoutside, please open a PR to add it here.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Welly

💻 📖 🚧

DmitryScaletta

🐛

vardani

🐛

Alexey Cherepanov

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

Keywords

FAQs

Package last updated on 06 Oct 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc