Skip to content

Instantly share code, notes, and snippets.

@roykho
Created August 3, 2025 15:19
Show Gist options
  • Select an option

  • Save roykho/738d7745e562cf14558ee44f9eb69282 to your computer and use it in GitHub Desktop.

Select an option

Save roykho/738d7745e562cf14558ee44f9eb69282 to your computer and use it in GitHub Desktop.
React - Handy click outside container handler
import { useEffect, useRef } from 'react';
const useClickOutside = (callback: () => void) => {
const ref = useRef<HTMLElement>(null);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
// If the ref exists and the clicked element is not inside the ref's element
if (ref.current && !ref.current.contains(event.target as Node)) {
callback(); // Execute the provided callback function
}
};
const handleKeyDown = (event: KeyboardEvent) => {
// Check if the escape key was pressed
if (event.key === 'Escape') {
callback(); // Execute the provided callback function
}
};
// Add event listeners to the document
document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('keydown', handleKeyDown);
// Clean up the event listeners when the component unmounts or dependencies change
return () => {
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('keydown', handleKeyDown);
};
}, [callback]); // Re-run effect if the callback function changes
return ref; // Return the ref to be attached to the target element
};
export default useClickOutside;
// USAGE:
Add a ref to the container you're targeting.
const component = () => {
const containerRef = useClickOutside(() => setShowContainer(false));
return (
<div ref={containerRef}>Hello</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment