@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
14
Maintainers
Readme
Welcome to @patrissoljuns/react-click-outside 🎉
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:
- Fork the repository and create a new branch for your changes.
- Install the necessary dependencies by running
npm install
oryarn install
. - Make your changes, ensuring that they adhere to the project's coding standards.
- Test your changes by running the appropriate test command (e.g.,
npm test
oryarn test
). You may also update tests. - Submit a pull request for your changes, and we'll review them as soon as possible.
📄 License
MIT © Patrissol KENFACK