1.0.10 • Published 5 years ago

react-use-click-away v1.0.10

Weekly downloads
8
License
MIT
Repository
github
Last release
5 years ago

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)

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.

Acknowledgements

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago