All Projects → wellyshen → React Cool Onclickoutside

wellyshen / React Cool Onclickoutside

Licence: mit
😎 🖱 React hook to listen for clicks outside of the component(s).

Programming Languages

typescript
32286 projects

Labels

Projects that are alternatives of or similar to React Cool Onclickoutside

window-scroll-position
React hook for Window scroll position
Stars: ✭ 81 (-72.54%)
Mutual labels:  hook
use-dencrypt-effect
⚛ A custom React hook generating crypting text effect.
Stars: ✭ 39 (-86.78%)
Mutual labels:  hook
Radioactive State
☢ Make Your React App Truly Reactive!
Stars: ✭ 273 (-7.46%)
Mutual labels:  hook
ezinject
Modular binary injection framework, successor of libhooker
Stars: ✭ 47 (-84.07%)
Mutual labels:  hook
hookr
PHP action and filter hook system
Stars: ✭ 39 (-86.78%)
Mutual labels:  hook
MouseInjectDetection
Simple method of checking whether or not mouse movement or buttons (<windows 10) are injected
Stars: ✭ 29 (-90.17%)
Mutual labels:  hook
use-bus
React hook to subscribe and dispatch events accros React components
Stars: ✭ 51 (-82.71%)
Mutual labels:  hook
Swr
React Hooks for data fetching
Stars: ✭ 20,348 (+6797.63%)
Mutual labels:  hook
next-use-contextual-routing
Generate contextual routing / modal routes paths for Next.js
Stars: ✭ 76 (-74.24%)
Mutual labels:  hook
React Loads
React Loads is a backend agnostic library to help with external data fetching & caching in your UI components.
Stars: ✭ 268 (-9.15%)
Mutual labels:  hook
LowLevelInput.Net
A thread safe and event driven LowLevelMouse and LowLevelKeyboard Hook
Stars: ✭ 32 (-89.15%)
Mutual labels:  hook
goverlay
DirectX hook and game overlay solution for Electron, Qt and CEF, just like discord/steam game overlay,inject any app to overlay in your game
Stars: ✭ 426 (+44.41%)
Mutual labels:  hook
Use Clipboard Copy
📋 Lightweight copy to clipboard hook for React
Stars: ✭ 256 (-13.22%)
Mutual labels:  hook
SandVXposed
Xposed environment without root (OS 5.0 - 12.0)
Stars: ✭ 241 (-18.31%)
Mutual labels:  hook
Mirage
kernel-mode Anti-Anti-Debug plugin. based on intel vt-x && ept technology
Stars: ✭ 272 (-7.8%)
Mutual labels:  hook
Beike AspectD
Flutter AOP framework.(Flutter面向切面库, 最新适配Flutter v2.5.3, null-safety)
Stars: ✭ 39 (-86.78%)
Mutual labels:  hook
blog
My Frontend Blog
Stars: ✭ 77 (-73.9%)
Mutual labels:  hook
Use Editable
A small React hook to turn elements into fully renderable & editable content surfaces, like code editors, using contenteditable (and magic)
Stars: ✭ 291 (-1.36%)
Mutual labels:  hook
Epic
Dynamic java method AOP hook for Android(continution of Dexposed on ART), Supporting 5.0~11
Stars: ✭ 3,434 (+1064.07%)
Mutual labels:  hook
Wechat tweak
♨️ iOS版功能最全的微信插件,支持最新版微信,具备自动抢红包,屏蔽消息和群消息,过滤特定的群聊,防止撤回消息,伪定位 (朋友圈和附近的人),修改微信运动步数和实时取景做聊天页的背景等功能。
Stars: ✭ 265 (-10.17%)
Mutual labels:  hook

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 npm bundle size MIT licensed All Contributors PRs welcome Twitter URL

Features

Requirement

To use react-cool-onclickoutside, you must use [email protected] 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" }
  );

  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.

Key Type Default Description
refs Array For some reasons, you can pass in your own ref(s) instead of using the built-in.
disabled boolean false Enable/disable the event listener.
eventTypes Array ['mousedown', 'touchstart'] Which events to listen for.
excludeScrollbar boolean false Whether or not to listen (ignore) to browser scrollbar clicks.
ignoreClass string ignore-onclickoutside To ignore certain elements during the event loop by the CSS class name that you defined.
detectIFrame boolean true To disable the feature of detecting iframe clicks.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Welly

💻 📖 🚧

DmitryScaletta

🐛

vardani

🐛

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].