react-use-click-away
a custom React effect for clicking away to close dropdowns
Explore the docs »
View Demo
·
Report Bug
·
Request Feature
Table of Contents
The Problem
In modern web applications, it is difficult to build a dropdown or other container that closes when you click away.
The Solution
react-use-click-away
is a custom React effect which allows you to easily close your dropdowns and other containers when clicking away.
Similar to useEffect
, you call it within a Hook component and it will help you hide and show your components based on where you click within your app.
Example
Using it in your application might look something like this:
{ const open setOpen = return <nav id='navbar'> <span id='toggle' onClick= >Menu</span> <div className=`inner-menu `> <ul className="nav-list"> <li>Page 1</li> <li>Page 2</li> </ul> </div> </nav> }
You call useClickAway
inside your function component and pass it an object with the following properties:
open
: the state value for the dropdown or container (boolean)setOpen
: the corresponding hook which updatesopen
(function)reactAppId
: the id on the div that wraps your entire app (string)clickable
: the elements that are clickable (i.e. clicking them won't close the dropdown or container) (array of strings)
Installation
You can install it using either of the following:
# Using npm npm install --save react-use-click-away # Using yarn yarn add --save react-use-click-away
Contributors
Thanks goes to these wonderful people (emoji key):
Tad Scritchfield 💻 🤔 👀 | JavaScript Joe 💻 🤔 📖 💡 |
License
Distributed under the MIT License. See LICENSE
for more information.