JAVASCRIPT
Custom useClickOutside Hook for Modals/Dropdowns
Create a `useClickOutside` custom React hook to detect clicks outside a referenced element, perfect for closing modals, dropdowns, or popovers.
import { useEffect } from 'react';
function useClickOutside(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
return ref;
}
// Example Usage:
// function DropdownMenu() {
// 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={{ border: '1px solid gray', padding: '10px', marginTop: '5px' }}>
// <p>Dropdown Item 1</p>
// <p>Dropdown Item 2</p>
// </div>
// )}
// </div>
// );
// }
How it works: The `useClickOutside` hook takes a `ref` (to the element you want to monitor) and a `handler` function. It attaches `mousedown` and `touchstart` event listeners to the document. If a click or touch event occurs outside the `ref`'s element or its children, the `handler` function is executed. This is ideal for dismissing UI elements like modals, tooltips, or dropdowns when the user clicks elsewhere.