Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@react-hooks-hub/use-click-outside

Keized2.5kMIT1.0.0TypeScript support: included

useClickOutside is a custom React hook designed for detecting clicks outside a specified element or set of elements.

react, react-hook, react hook, hook, react click outside, click-outside hook, click outside, outside click, click detection

readme

Use Click Outside

`@react-hooks-hub/use-click-outside` is a custom React hook designed for detecting clicks outside a specified element or set of elements. Easy to integrate and use, this hook is perfect for scenarios like closing dropdown menus, popups, or modals when a user clicks outside these components. It supports multiple referenced elements and provides a straightforward interface for adding custom click outside event handling. Compatible with React and TypeScript, useClickOutside is an essential tool for enhancing user interaction in your web applications.

NPM version CI status   Bundlephobia  

@react-hooks-hub/use-click-outside

Installation

Use your preferred package manager to install @react-hooks-hub/use-click-outside:

npm install @react-hooks-hub/use-click-outside
# or
yarn add @react-hooks-hub/use-click-outside

Usage

Import and use the useClickOutside hook in your component:

import React, { useState, useRef } from 'react';
import { useClickOutside } from '@react-hooks-hub/use-click-outside';

function DropdownMenu() {
    const [isOpen, setIsOpen] = useState(false);
    const menuRef = useRef(null);

    useClickOutside([menuRef], (isOutside) => {
      setIsOpen(isOutside)
    });

    return (
        <div>
            <button onClick={() => setIsOpen(!isOpen)}>Toggle Menu</button>
            {isOpen && (
                <div ref={menuRef}>
                    {/* content */}
                </div>
            )}
        </div>
    );
}

export default DropdownMenu;