JAVASCRIPT
Detect Clicks Outside a Component with a React Hook
Create a `useClickOutside` React hook to easily handle events when a user clicks anywhere outside a specified DOM element, perfect for dropdowns and modals.
import { useEffect, useRef } from 'react';
const useClickOutside = (ref, handler) => {
useEffect(() => {
const listener = (event) => {
// Do nothing if clicking ref's element or descendent 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]); // Only re-run if ref or handler changes
};
export default useClickOutside;
// Example Usage:
/*
function Dropdown() {
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useRef(null);
useClickOutside(dropdownRef, () => setIsOpen(false));
return (
<div ref={dropdownRef} style={{ border: '1px solid black', padding: '10px' }}>
<button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
{isOpen && (
<div style={{ background: '#eee', padding: '10px', marginTop: '5px' }}>
Dropdown Content
</div>
)}
</div>
);
}
*/
How it works: The `useClickOutside` hook takes a `ref` to the target element and a `handler` function. It attaches `mousedown` and `touchstart` event listeners to the entire `document`. When an event occurs, it checks if the clicked target is *inside* the referenced element. If not, and the `ref` exists, the provided `handler` is executed. This is ideal for closing dropdowns or modals when the user clicks elsewhere.