File tree Expand file tree Collapse file tree 2 files changed +16
-2
lines changed Expand file tree Collapse file tree 2 files changed +16
-2
lines changed Original file line number Diff line number Diff line change 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" ,
Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments