JAVASCRIPT
Custom React Hook to Detect Clicks Outside an Element
Implement a React hook to easily detect clicks occurring outside a specified DOM element. Perfect for closing modals, dropdowns, or popovers when users click away.
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
// Example Usage:
// function Dropdown() {
// const [isOpen, setIsOpen] = useState(false);
// const ref = useRef();
// useClickOutside(ref, () => setIsOpen(false));
//
// return (
// <div ref={ref}>
// <button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
// {isOpen && <div>Dropdown Content</div>}
// </div>
// );
// }
How it works: The `useClickOutside` hook takes a React ref and a handler function. It attaches `mousedown` and `touchstart` event listeners to the `document`. When an event occurs, it checks if the clicked target is outside the element referenced by the `ref`. If it is, the provided `handler` function is executed. This is commonly used for dismissing UI elements like modals, dropdowns, or sidebars when a user clicks anywhere else on the page.