@react-hooks-hub/use-click-outside
v0.0.2
Published
useClickOutside is a custom React hook designed for detecting clicks outside a specified element or set of elements.
Downloads
415
Maintainers
Readme
@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;