JAVASCRIPT
Detect Clicks Outside a React Element
Implement logic to detect when a user clicks outside a specific React component, perfect for closing modals, dropdowns, or popovers when the focus is lost.
import { useEffect } from 'react';
function useClickOutside(ref, handler) {
useEffect(() => {
const listener = (event) => {
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]);
}
// Example Usage:
// function Dropdown() {
// const [isOpen, setIsOpen] = useState(false);
// const dropdownRef = useRef(null);
// useClickOutside(dropdownRef, () => {
// if (isOpen) setIsOpen(false);
// });
// return (
// <div ref={dropdownRef}>
// <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
// {isOpen && (
// <div style={{ border: '1px solid black', padding: '10px', marginTop: '5px' }}>
// Dropdown Content
// </div>
// )}
// </div>
// );
// }
How it works: The `useClickOutside` hook allows you to execute a function (`handler`) whenever a click or touch event occurs *outside* of a specified DOM element, referenced by a `useRef`. It attaches `mousedown` and `touchstart` event listeners to the `document`. Inside the listener, it checks if the clicked target is within the referenced element. If not, the provided `handler` function is called. The `useEffect` cleanup ensures event listeners are properly removed when the component unmounts.