Skip to content

Commit 44dff6b

Browse files
committed
Listen for clicks outside of the menu and close the dropdown
1 parent 65a3145 commit 44dff6b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/use-dropdown-menu.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,41 @@ export default function useDropdownMenu(itemCount: number) {
3939
if (isOpen) {
4040
moveFocus(0);
4141
}
42+
43+
44+
// This function is designed to handle every click
45+
const handleEveryClick = (event: MouseEvent) => {
46+
// Ignore if the menu isn't open
47+
if (!isOpen) {
48+
return;
49+
}
50+
51+
// Make this happen asynchronously
52+
setTimeout(() => {
53+
// Type guard
54+
if (!(event.target instanceof Element)) {
55+
return;
56+
}
57+
58+
59+
// Ignore if we're clicking inside the menu
60+
if (event.target.closest('[role="menu"]')) {
61+
return;
62+
}
63+
64+
65+
// Hide dropdown
66+
setIsOpen(false);
67+
}, 10);
68+
};
69+
70+
71+
// Add listener
72+
document.addEventListener('click', handleEveryClick);
73+
74+
75+
// Return function to remove listener
76+
return () => document.removeEventListener('click', handleEveryClick);
4277
}, [isOpen]);
4378

4479
// Create a handler function for the button's clicks and keyboard events

0 commit comments

Comments
 (0)