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

@patrissoljuns/react-click-outside

v1.0.0

Published

A React component and hook to handle clicks outside a specified element, useful for closing dropdowns, modals, and more.

Downloads

18

Readme

Welcome to @patrissoljuns/react-click-outside 🎉

codecov

Looking for an easy and efficient way to handle click-away interactions in your React application? Look no further! Introducing @patrissoljuns/react-click-outside, a lightweight and powerful package that offers a hassle-free solution for handling click-away events in React applications. Whether you're working on dropdowns, modals, or any other UI components that need to close when a user interacts outside of them, this package has got your back.

🔥 Features

  • Versatile: Support for both functional components (hooks) and class components. Choose the method that works best for you!
  • Flexible: Customizable event types (click, mousedown, mouseup, keydown, touchstart, etc.)
  • Scoped: Define the target element or document where the event listeners will be attached, making it ideal for restricting click-away detection to a particular section or container in your application.
  • Optimized: Streamlined event handling and clean-up ensure top-notch performance and silky-smooth user experiences.
  • Type-safe: Crafted with TypeScript for built-in type safety.

📦 Installation

npm install @patrissoljuns/react-click-outside
# or
yarn add @patrissoljuns/react-click-outside

🚀 Usage

Declarative Component

Here's a simple example of using the ClickOutsideListener component to close a dropdown menu:

import React, { useState } from 'react';
import ClickOutsideListener from '@patrissoljuns/react-click-outside';

const MyComponent = () => {
  const [dropdownOpen, setDropdownOpen] = useState(false);

  const handleClickOutside = () => {
    setDropdownOpen(false);
  };

  const toggleDropdown = () => {
    setDropdownOpen(!dropdownOpen);
  };

  return (
    <div>
      <button onClick={toggleDropdown}>Toggle Dropdown</button>
      {dropdownOpen && (
        <ClickOutsideListener onClickOutside={handleClickOutside}>
          <div className="dropdown">
            {/* Dropdown content */}
            Click outside this element to close it!
          </div>
        </ClickOutsideListener>
      )}
    </div>
  );
};

useClickOutsideListener Hook

Alternatively, you can use the useClickAwayListener hook to programmatically handle click-away events

import React, { useState } from 'react';
import { useClickOutsideListener } from '@patrissoljuns/react-click-outside';

const ExampleComponent = () => {
  const [showDrawer, setShowDrawer] = useState(false);
  
  const containerRef = useClickOutsideListener<HTMLDivElement>({
    onClickOutside: () => setShowDrawer(false), 
    events: ['keydown', 'touchstart']
  });

  return (
    <div ref={containerRef}>
      <button onClick={() => setShowDrawer(true)}>Toggle drawer</button>
      {showDrawer && <div>My beautiful drawer</div>}
    </div>
  );
};

📚 API

useClickOutsideListener

| Prop | Type | Description | |----------|:-------------:|:-------------:| | onClickOutside required | (event: MouseEvent | TouchEvent | KeyboardEvent | FocusEvent) => void | A callback function that is triggered when an event specified in the events prop occurs outside the children element. It receives the event object as its argument, allowing you to perform custom actions based on the event type, target, or other properties | events Default to ['mousedown'] | Array<'mousedown' | 'mouseup' | 'mouseover' | 'click' | 'touchstart' | 'touchend' | 'keydown' | 'keyup' | 'focus' | 'blur'> | An array of event types to listen for. This allows you to customize the events that trigger the onClickOutside callback | | scope Default to document | HTMLElement | Document | null | An optional parameter that allows you to specify the target element, document, or null where the event listeners will be attached. This can be useful in cases where you want to limit the click-away detection to a specific section or container of your application. If scope is set to null, no event listener will be attached. If scope is undefined, the document will be used as the default value. This flexibility helps handling the initial state of refs more easily and avoid potential issues or unexpected behavior when working with the useClickOutsideListener hook. |

ClickOutsideListener

Same with useClickOutsideListener above plus the following:

| Prop | Type | Description | |----------|:-------------:|:-------------:| | children required | React.ReactElement | A single React element that the ClickOutsideListener will wrap. This element will be monitored for click events happening outside of it. The ClickOutsideListener will execute the provided onClickOutside callback when such an event occurs | | wrapperComponent | React.ElementType | An optional custom component that will be used as the wrapper for the children element. By default, ClickOutsideListener uses a React fragment to avoid altering the DOM structure. However, if you need to use a specific HTML element or custom component as the wrapper, you can provide it through this prop | | wrapperProps | React.HTMLAttributes<HTMLElement> | Optional object containing any additional props to apply to the wrapperComponent if present

📖 Examples

import React, { useState } from 'react';
import ClickOutsideListener, { UseClickOutsideListenerOptions } from '@patrissoljuns/react-click-outside';

const App = () => {
    const [isModalOpen, setIsModalOpen] = useState(false);

    const closeModal: UseClickOutsideListenerOptions['onClickOutside'] = (event) => {
        if (event instanceof KeyboardEvent && (event.key === 'p' || event.key === 'Escape')) {
            setIsModalOpen(false);
        }
    };

    const openModal = () => {
        setIsModalOpen(true);
    };

    return (
        <div>
            <button onClick={openModal}>Open Modal</button>
            {isModalOpen && (
                <ClickOutsideListener onClickOutside={closeModal} events={['keydown']}>
                    <div className="modal">
                        <h2>Modal Title</h2>
                        <p>Modal content...</p>
                    </div>
                </ClickOutsideListener>
            )}
        </div>
    );
};

export default App;
import React, {useState} from 'react';
import useClickOutsideListener from "@patrissoljuns/react-click-outside";
import { Button, Popover, MenuList, MenuItem } from '@mui/material';

const MuiPopoverExample: React.FC = () => {
    const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);

    const handleClick = (event: React.MouseEvent<HTMLElement>) => {
        setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
        setAnchorEl(null);
    };

    const open = Boolean(anchorEl);
    const id = open ? 'popover-example' : undefined;

    return (
        <div>
            <Button variant="contained" color="primary" onClick={handleClick}>
                Open Popover
            </Button>

            <Popover
                id={id}
                open={open}
                anchorEl={anchorEl}
                onClose={() => null}
                anchorOrigin={{
                    vertical: 'bottom',
                    horizontal: 'center',
                }}
                transformOrigin={{
                    vertical: 'top',
                    horizontal: 'center',
                }}
            >
                <ClickOutsideListener
                    onClickOutside={handleClose}
                    events={['keyup']}
                >
                    <MenuList id="my-menu">
                        <MenuItem onClick={handleClose}>Option 1</MenuItem>
                        <MenuItem onClick={handleClose}>Option 2</MenuItem>
                        <MenuItem onClick={handleClose}>Option 3</MenuItem>
                    </MenuList>
                </ClickOutsideListener>
            </Popover>
        </div>
    );
};
import React, { useState } from 'react';
import useClickOutsideListener from '@patrissoljuns/react-click-outside';
import { Button, Typography, Card } from 'antd';

const TouchPanelExample: React.FC = () => {
    const [isOpen, setIsOpen] = useState(false);

    const handleOpen = () => {
        setIsOpen(true);
    };

    const handleClose = () => {
        setIsOpen(false);
    };

    const panelRef = useClickOutsideListener({
        onClickOutside: handleClose,
        events: ['touchstart'],
    });

    return (
        <div>
            <Button type="primary" onClick={handleOpen}>
                Open Panel
            </Button>
            {isOpen && (
                <div
                    style={{
                        position: 'absolute',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%, -50%)',
                    }}
                    ref={panelRef}
                >
                    <Card title="Touch Panel" bordered={false}>
                        <Typography.Text>
                            Touch anywhere outside this panel to close it.
                        </Typography.Text>
                    </Card>
                </div>
            )}
        </div>
    );
};

🙌 Contributing

We welcome your contributions! To get started, follow these steps:

  1. Fork the repository and create a new branch for your changes.
  2. Install the necessary dependencies by running npm install or yarn install.
  3. Make your changes, ensuring that they adhere to the project's coding standards.
  4. Test your changes by running the appropriate test command (e.g., npm test or yarn test). You may also update tests.
  5. Submit a pull request for your changes, and we'll review them as soon as possible.

📄 License

MIT © Patrissol KENFACK