use-close-modal
v1.0.2
Published
The useOutsideClick hook is a React utility that allows you to detect when a user clicks outside a specified element (usually a modal or a dropdown) and trigger a callback when such a click is detected. This can be particularly useful for implementing fea
Downloads
12
Maintainers
Readme
useOutsideClick Hook
The useOutsideClick hook is a React utility that allows you to detect when a user clicks outside a specified element (usually a modal or a dropdown) and trigger a callback when such a click is detected. This can be particularly useful for implementing features like closing a modal when the user clicks outside of it.
Usage
1. installation:
using npm
npm install use-close-modal
using yarn
yarn add use-close-modal
2. Import the hook:
Import the useOutsideClick
hook into your React component file where you want to use it.
import useOutsideClick from "use-close-modal";
3. Use the hook:
function MyComponent() {
const closeModal = () => {
// Handle modal closing logic here
};
const modalContainerRef = useOutsideClick({
onClose: closeModal,
});
return <div ref={modalContainerRef}>{/* Your modal content */}</div>;
}
In this example, the closeModal
function will be called when a click occurs outside of the element referenced by modalContainerRef
.
4. Props
The useOutsideClick
hook accepts an object with the following prop:
-`onClose` (function): This is the callback function that will be executed when a click occurs outside of the specified element. You can define your custom logic here, such as closing a modal or performing other actions.
Acknowledgments
This hook was inspired by the need to easily handle outside click events in React applications.