JAVASCRIPT
Detect Clicks Outside an Element with useOutsideClick React Hook
Create a reusable React hook to easily detect when a user clicks outside a specified DOM element, perfect for closing modals, dropdowns, or popovers.
import { useEffect, useRef } from 'react';
function useOutsideClick(callback) {
const ref = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
callback();
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [callback]);
return ref;
}
// How to use it:
// function DropdownMenu() {
// const [isOpen, setIsOpen] = useState(false);
// const dropdownRef = useOutsideClick(() => setIsOpen(false));
// return (
// <div ref={dropdownRef} style={{ position: 'relative', display: 'inline-block' }}>
// <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
// {isOpen && (
// <ul style={{ position: 'absolute', background: 'lightgray', padding: '10px' }}>
// <li>Item 1</li>
// <li>Item 2</li>
// </ul>
// )}
// </div>
// );
// }
How it works: This `useOutsideClick` hook provides a convenient way to trigger a function whenever a click occurs outside a specific element. It uses `useRef` to create a reference to the target DOM element. An `useEffect` hook then attaches a global `mousedown` event listener to the document. When a click occurs, it checks if the clicked element is outside the referenced element using `ref.current.contains(event.target)`. If it's an outside click, the provided `callback` function is executed, and the event listener is cleaned up when the component unmounts.