npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-detect-click-outside

v1.1.7

Published

Detects clicks outside React components, and also handles keypresses.

Downloads

123,046

Readme

react-detect-click-outside

A lightweight React hook that detects clicks outside elements and triggers a callback. Can also detect keypresses.

📈  Over 7,600 weekly users (as of June 2022).

👍  Great for toggling dropdowns!

Notice: This package is looking for maintainers! Due to my professional and personal commitments, I don't have a whole lot of time to devote to maintaining this library. Some users have pointed out a few issues in the Github repo - feel free to take a stab at them!

Table of Contents

Features

  • 🖱 💻  Detects clicks outside an element and/or keypresses.
  • 🔨  Customizable: disable clicks, disable keypresses, or specify keys that will trigger the callback
  • 🎣  Built with React hooks
  • 🔥  Written in TypeScript

Installation

Install with Yarn:

yarn add react-detect-click-outside

Or with NPM:

npm i react-detect-click-outside

Import into your component like so:

import { useDetectClickOutside } from 'react-detect-click-outside';

Usage

Here's an example of how to use the hook.

This library was built with UI features like dropdowns in mind. Below is a quick and functioning example of how to include it in a dropdown component:

const Dropdown = ({ closeDropdown }) => {
  const ref = useDetectClickOutside({ onTriggered: closeDropdown });
  return (
    <div className="dropdown" ref={ref}>
      <p>This is a dropdown!</p>
    </div>
  );
};

How to implement the hook inside a function component:

  1. Assign the hook to a variable before the component's return statement (above we use ref). Pass an empty object into the hook as an argument.
const ref = useDetectClickOutside({});
  1. The object you just passed into the useDetectClickOutside hook requires a property called onTriggered. The value of onTriggered must be a function — by default, it'll be called anytime a user clicks outside the component or hits the Escape key.

    In the example above, we used a function called closeToggle. This function is passed down from a parent component (let's call it Container) and controls a piece of state that determines whether the Dropdown component is visible.

    Here's a quick, trimmed-down example:

    const Container = () => {
        const [displayDropdown, setDisplayDropdown] = useState(false);
    
        const closeDropdown = () => {
            setDisplayDropdown(false);
        }
        return (
            { displayDropdown && <Dropdown/> }
        )
    }

    Now, go ahead and pass your callback into the useDetectClickOutside hook!

    const ref = useDetectClickOutside({ onTriggered: closeDropdown });
    1. Assign your ref constant (or whatever constant you assigned the useDetectClickOutside hook to) as a ref to the outermost element returned by your target component.
    return (
      <div className="dropdown" ref={ref}>
        <p>This is a dropdown!</p>
      </div>
    );

    Here's what the whole component should look like now:

    const Dropdown = ({ closeDropdown }) => {
      const ref = useDetectClickOutside({ onTriggered: closeDropdown });
      return (
        <div className="dropdown" ref={ref}>
          <p>This is a dropdown!</p>
        </div>
      );
    };

    Congrats! Your useDetectClickOutside should now trigger anytime a user clicks outside your component or presses the Escape key.

    Want to customize your hook? Check out some of the additional options below.

Options

The object passed into the useDetectClickOutside hook accepts the following properties. Note that only onTriggered is required.

onTriggered (required)

Type: () => void

A callback function, e.g. one that toggles the visibility of the component. By default, this function is triggered by a click outside the component, and by an Escape keyup event.

Example:

const ref = useDetectClickOutside({ onTriggered: closeDropdown });

disableClick (optional)

Type: boolean

When passed to the hook, this option will prevent clicks from triggering the onTriggered callback when the component is in the DOM. This option is disabled by default.

Example:

const ref = useDetectClickOutside({
  onTriggered: closeDropdown,
  disableClick: true,
});

disableTouch (optional)

Type: boolean

When passed to the hook, this option will prevent touch events from triggering the onTriggered callback when the component is in the DOM. This option is disabled by default.

Example:

const ref = useDetectClickOutside({
  onTriggered: closeDropdown,
  disableTouch: true,
});

disableKeys (optional)

Type: boolean

This option will prevent keypresses from triggering the onTriggered callback when the component is in the DOM. This option is disabled by default.

Example:

const ref = useDetectClickOutside({
  onTriggered: closeDropdown,
  disableKeys: true,
});

allowAnyKey (optional)

Type: boolean

This option will let any keypress trigger the onTriggered callback when the component is in the DOM - not just the Escape key. This option is disabled by default.

Example:

const ref = useDetectClickOutside({
  onTriggered: closeDropdown,
  allowAnyKey: true,
});

triggerKeys (optional)

Type: string[]

An array of key values that will trigger the onTriggered callback.

Example:

const ref = useDetectClickOutside({
  onTriggered: closeDropdown,
  triggerKeys: ['Enter', 'Tab', 'x'],
});

Note: This option overrides the default hook behavior of triggering the onTriggered callback with the Escape key. If you still wish to trigger the onTriggered function with Escape, you need to add it to the array (e.g. triggerKeys=['Escape', 'Enter']).

Requirements

You must be using React 16.8.0 or later. In other words, your version of React must support hooks.