JAVASCRIPT
Detect Clicks Outside a Component with a Custom Hook
Implement a reusable custom React hook to detect clicks outside a specified DOM element, perfect for closing modals, dropdowns, or tooltips efficiently.
import { useEffect } from 'react';
function useOutsideClick(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]); // Only re-run if ref or handler changes
// Example Usage:
/*
import React, { useRef, useState } from 'react';
function Dropdown() {
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useRef(null);
useOutsideClick(dropdownRef, () => {
if (isOpen) 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 grey', marginTop: '5px', padding: '10px' }}>
Dropdown Content
</div>
)}
</div>
);
}
*/
}
How it works: The `useOutsideClick` hook attaches event listeners to the `document` to detect clicks or touch events. If the event target is outside the `ref.current` element, the provided `handler` function is executed. This is commonly used for closing UI elements like dropdowns, modals, or sidebars when a user clicks anywhere outside their boundaries.