JAVASCRIPT
`useOnClickOutside` Hook for Click Detection
Build a `useOnClickOutside` custom React hook to detect clicks outside a specified DOM element, perfect for closing modals, dropdowns, or popovers.
import { useEffect } from 'react';
function useOnClickOutside(ref, handler) {
useEffect(() => {
const listener = (event) => {
// Do nothing if clicking ref's element or descendant elements
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
};
}, [ref, handler]); // Reload only if ref or handler changes
}
// Example Usage:
/*
function Dropdown() {
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useRef();
useOnClickOutside(dropdownRef, () => setIsOpen(false));
return (
<div ref={dropdownRef}>
<button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
{isOpen && (
<div style={{ border: '1px solid black', padding: '10px', marginTop: '5px' }}>
Dropdown Content
</div>
)}
</div>
);
}
*/
How it works: The `useOnClickOutside` hook provides a way to detect clicks that occur outside a referenced DOM element. It attaches `mousedown` and `touchstart` event listeners to the `document`. When an event occurs, it checks if the clicked target is *inside* the `ref.current` element. If it's not, the provided `handler` function is executed, which is typically used to close or hide the target component. Event listeners are cleaned up when the component unmounts.