JAVASCRIPT
React useOnClickOutside Hook for Detecting Clicks
Implement a versatile React useOnClickOutside hook to detect clicks outside a specified DOM element, essential 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(null);
// useOnClickOutside(dropdownRef, () => setIsOpen(false));
// return (
// <div ref={dropdownRef}>
// <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
// {isOpen && (
// <div style={{ border: '1px solid black', padding: '10px' }}>
// Dropdown Content
// </div>
// )}
// </div>
// );
// }
How it works: The `useOnClickOutside` hook allows you to execute a function when a click or touch event occurs outside of a referenced DOM element. It's commonly used for components like dropdowns, modals, or context menus that need to close or hide when the user interacts with the rest of the page. It attaches event listeners to the document and cleans them up on unmount.