react-use-click-away
v1.0.10
Published
a custom React effect for clicking away to close dropdowns
Downloads
13
Readme
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:
import React, { useState } from "react"
import useClickAway from "react-use-click-away"
function NavBar () {
const [open, setOpen] = useState(false)
useClickAway({
open,
setOpen,
reactAppId: "my-react-app",
clickable: ["navbar"]
})
return (
<nav id='navbar'>
<span id='toggle' onClick={() => setOpen(!open)}>Menu</span>
<div className={`inner-menu ${open ? "active" : ""}`}>
<ul className="nav-list">
<li>Page 1</li>
<li>Page 2</li>
</ul>
</div>
</nav>
)
}
export default NavBar
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):
License
Distributed under the MIT License. See LICENSE
for more information.