Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

wellyshen/react-cool-onclickoutside

This is a Reacthook 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 thefeatures section to learn more.

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

❤️ it? ⭐️ it onGitHub orTweet about it.

build statuscoverage statusnpm versionnpm downloadsnpm downloadsgzip sizeAll ContributorsPRs welcomeTwitter URL

Features

Requirement

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

Installation

This package is distributed vianpm.

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

Usage

Common use case.

import{useState}from"react";importuseOnclickOutsidefrom"react-cool-onclickoutside";constDropdown=()=>{const[openMenu,setOpenMenu]=useState(false);constref=useOnclickOutside(()=>{setOpenMenu(false);});consthandleClickBtn=()=>{setOpenMenu(!openMenu);};return(<div><buttononClick={handleClickBtn}>Button</button>{openMenu&&<divref={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";importuseOnclickOutsidefrom"react-cool-onclickoutside";constApp=()=>{const[showTips,setShowTips]=useState(true);constref=useOnclickOutside(()=>{setShowTips(false);});return(<div>{showTips&&(<><divref={ref}>Tooltip 1</div><divref={ref}>Tooltip 2</div></>)}</div>);};

Ignore Elements by CSS Class Name

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

import{useState}from"react";importuseOnclickOutsidefrom"react-cool-onclickoutside";// Use the default CSS class nameconstApp=()=>{constref=useOnclickOutside(()=>{// Do something...});return(<div><divref={ref}>I'm a 🍕</div><div>Click me will trigger the event's callback</div><divclassName="ignore-onclickoutside">        Click me won't trigger the event's callback</div></div>);};// Use your own CSS class nameconstApp=()=>{constref=useOnclickOutside(()=>{// Do something...},{ignoreClass:"my-ignore-class",// Or ["class-1", "class-2"]});return(<div><divref={ref}>I'm a 🍕</div><div>Click me will trigger the event's callback</div><divclassName="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 thedisabled option for you. Once you set it totrue, the callback won’t be triggered.

import{useState}from"react";importuseOnclickOutsidefrom"react-cool-onclickoutside";constApp=()=>{const[disabled,setDisabled]=useState(false);constref=useOnclickOutside(()=>{// Do something...},{ disabled});consthandleBtnClick=()=>{setDisabled(true);};return(<div><buttononClick={handleBtnClick}>        Stop listening for outside clicks</button><divref={ref}>I'm a 🍎</div></div>);};

Use Your Ownref

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.

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

Detecting Iframe Clicks

Clicks on an<iframe> element won't triggerdocument.documentElement listeners, because it's literally different page with different security domain. However, when clicking on an iframe movesfocus to its content's window that triggers the mainwindow.blur event.react-cool-onclickoutside in conjunction theblur event withdocument.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 thedetectIFrame tofalse if you find it conflicting with your use-case.

API

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

You must register theref and pass thecallback to use this hook. Moreover you can access theevent object via the callback's parameter, default will beMouseEvent orTouchEvent.

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

Theoptions object contains the following keys.

KeyTypeDefaultDescription
refsArrayForsome reasons, you can pass in your ownref(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 ofdetecting iframe clicks.

Articles / Blog Posts

💡 If you have written any blog post or article aboutreact-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 theall-contributors specification. Contributions of any kind welcome!

About

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

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

    Contributors7


    [8]ページ先頭

    ©2009-2025 Movatter.jp