JAVASCRIPT
React useOutsideClick Hook for Detecting Clicks Outside an Element
Implement click-outside functionality for modals, dropdowns, and popovers with a reusable `useOutsideClick` React hook, enhancing interactive UI components.
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]);
}
// Example Usage:
/*
import React, { useRef, useState } from 'react';
function Dropdown() {
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useRef(null);
useOutsideClick(dropdownRef, () => 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: 'white', border: '1px solid gray', padding: '10px' }}>
<li>Item 1</li>
<li>Item 2</li>
</ul>
)}
</div>
);
}
*/
How it works: The `useOutsideClick` hook detects when a user clicks outside a specified DOM element. It takes a `ref` to the target element and a `handler` function as arguments. When a 'mousedown' or 'touchstart' event occurs on the document, the hook checks if the click target is outside the referenced element. If it is, the `handler` function is executed. This is commonly used to close modals, dropdowns, or popovers when a user interacts with the surrounding content, ensuring a robust user experience.