Skip to content

Commit

Permalink
Merge pull request #293 from sparksuite/fix-listener-added-and-remove…
Browse files Browse the repository at this point in the history
…d-wrong-order

Fix listener added and removed wrong order
  • Loading branch information
WesCossick authored Jan 21, 2022
2 parents 8f8c123 + 65ca9b2 commit bb3e929
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-accessible-dropdown-menu-hook",
"version": "3.1.0",
"version": "3.2.0",
"description": "A simple Hook for creating fully accessible dropdown menus in React",
"main": "dist/use-dropdown-menu.js",
"types": "dist/use-dropdown-menu.d.ts",
Expand Down
16 changes: 15 additions & 1 deletion src/use-dropdown-menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ export default function useDropdownMenu<ButtonElement extends HTMLElement = HTML
return;
}

// Initialize object to track if the removal happens before the addition of the event listener
// -> We're using an object here so that arrow functions below capture the reference and not the value
const removalTracker = {
removed: false,
};

// This function is designed to handle every click
const handleEveryClick = (event: MouseEvent): void => {
// Make this happen asynchronously
Expand All @@ -100,11 +106,19 @@ export default function useDropdownMenu<ButtonElement extends HTMLElement = HTML
// Add listener
// -> Force it to be async to fix: https://github.com/facebook/react/issues/20074
setTimeout(() => {
if (removalTracker.removed) {
return;
}

document.addEventListener('click', handleEveryClick);
}, 1);

// Return function to remove listener
return (): void => document.removeEventListener('click', handleEveryClick);
return (): void => {
removalTracker.removed = true;

document.removeEventListener('click', handleEveryClick);
};
}, [isOpen]);

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

0 comments on commit bb3e929

Please sign in to comment.