diff --git a/package.json b/package.json index 98bb090..9df4301 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-accessible-dropdown-menu-hook", - "version": "2.1.1", + "version": "2.1.2", "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", diff --git a/src/use-dropdown-menu.ts b/src/use-dropdown-menu.ts index 31c63df..6eabc20 100644 --- a/src/use-dropdown-menu.ts +++ b/src/use-dropdown-menu.ts @@ -55,13 +55,13 @@ export default function useDropdownMenu(itemCount: number) { // Handle listening for clicks and auto-hiding the menu useEffect(() => { + // Ignore if the menu isn't open + if (!isOpen) { + return; + } + // This function is designed to handle every click const handleEveryClick = (event: MouseEvent) => { - // Ignore if the menu isn't open - if (!isOpen) { - return; - } - // Make this happen asynchronously setTimeout(() => { // Type guard @@ -80,7 +80,10 @@ export default function useDropdownMenu(itemCount: number) { }; // Add listener - document.addEventListener('click', handleEveryClick); + // -> Force it to be async to fix: https://github.com/facebook/react/issues/20074 + setTimeout(() => { + document.addEventListener('click', handleEveryClick); + }, 1); // Return function to remove listener return () => document.removeEventListener('click', handleEveryClick);