Skip to content

Commit bb3e929

Browse files
authored
Merge pull request #293 from sparksuite/fix-listener-added-and-removed-wrong-order
Fix listener added and removed wrong order
2 parents 8f8c123 + 65ca9b2 commit bb3e929

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-accessible-dropdown-menu-hook",
3-
"version": "3.1.0",
3+
"version": "3.2.0",
44
"description": "A simple Hook for creating fully accessible dropdown menus in React",
55
"main": "dist/use-dropdown-menu.js",
66
"types": "dist/use-dropdown-menu.d.ts",

src/use-dropdown-menu.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,12 @@ export default function useDropdownMenu<ButtonElement extends HTMLElement = HTML
7878
return;
7979
}
8080

81+
// Initialize object to track if the removal happens before the addition of the event listener
82+
// -> We're using an object here so that arrow functions below capture the reference and not the value
83+
const removalTracker = {
84+
removed: false,
85+
};
86+
8187
// This function is designed to handle every click
8288
const handleEveryClick = (event: MouseEvent): void => {
8389
// Make this happen asynchronously
@@ -100,11 +106,19 @@ export default function useDropdownMenu<ButtonElement extends HTMLElement = HTML
100106
// Add listener
101107
// -> Force it to be async to fix: https://github.com/facebook/react/issues/20074
102108
setTimeout(() => {
109+
if (removalTracker.removed) {
110+
return;
111+
}
112+
103113
document.addEventListener('click', handleEveryClick);
104114
}, 1);
105115

106116
// Return function to remove listener
107-
return (): void => document.removeEventListener('click', handleEveryClick);
117+
return (): void => {
118+
removalTracker.removed = true;
119+
120+
document.removeEventListener('click', handleEveryClick);
121+
};
108122
}, [isOpen]);
109123

110124
// Disable scroll when the menu is opened, and revert back when the menu is closed

0 commit comments

Comments
 (0)