Skip to content
master
Switch branches/tags
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
src
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

react-use-click-away


Logo

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:

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 updates open (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)

See a live demo here:

Edit react-use-click-away

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
Tad Scritchfield

💻 🤔 👀
JavaScript Joe
JavaScript Joe

💻 🤔 📖 💡

License

Distributed under the MIT License. See LICENSE for more information.

Acknowledgements