Initial commit
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
# useOutsideClick
|
||||
|
||||
Detects clicks and touches outside a referenced element and calls a callback.
|
||||
|
||||
## Signature
|
||||
|
||||
```ts
|
||||
function useOutsideClick(callback: () => void): React.RefObject<HTMLDivElement>;
|
||||
```
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| ---------- | ------------ | ------------------------------------------------ |
|
||||
| `callback` | `() => void` | Called when a click/touch occurs outside the ref |
|
||||
|
||||
Returns a `ref` to attach to the element you want to monitor.
|
||||
|
||||
## Usage
|
||||
|
||||
```tsx
|
||||
function Dropdown({ onClose }: { onClose: () => void }) {
|
||||
const ref = useOutsideClick(onClose);
|
||||
|
||||
return (
|
||||
<div ref={ref}>
|
||||
<p>Dropdown content</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Listens to both `mouseup` and `touchend` to cover desktop and mobile.
|
||||
- If `callback` changes on every render, wrap it in `useCallback` to avoid resetting listeners unnecessarily.
|
||||
- Client-only (`'use client'`).
|
||||
@@ -0,0 +1 @@
|
||||
export * from './useOutsideClick';
|
||||
@@ -0,0 +1,25 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
export const useOutsideClick = (callback: () => void) => {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent | TouchEvent) => {
|
||||
if (ref.current && !ref.current.contains(event.target as Node)) {
|
||||
callback();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mouseup', handleClickOutside);
|
||||
document.addEventListener('touchend', handleClickOutside);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mouseup', handleClickOutside);
|
||||
document.removeEventListener('touchend', handleClickOutside);
|
||||
};
|
||||
}, [callback]);
|
||||
|
||||
return ref;
|
||||
};
|
||||
Reference in New Issue
Block a user