diff --git a/src/hooks/useFocusTrap.ts b/src/hooks/useFocusTrap.ts index 297e949..22b41a4 100644 --- a/src/hooks/useFocusTrap.ts +++ b/src/hooks/useFocusTrap.ts @@ -59,6 +59,14 @@ export function useFocusTrap(locked = false, options: Use [getFocusableElements, locked], ); + const getTarget = (e: any) => { + let target = e.target; + if (e.composed) { + target = e.composedPath()[0]; + } + return target; + }; + // Ensure that user can not focus outside of lock. If an attempt is made // and focusable elements exist inside, will focus first element inside. const checkFocus = useCallback( @@ -68,10 +76,12 @@ export function useFocusTrap(locked = false, options: Use // Blur focus target if no focusable elements. const focusableElements = getFocusableElements(); - if (!focusableElements.length) return (event.target as HTMLElement | null)?.blur(); + const target = getTarget(event); + + if (!focusableElements.length) return (target as HTMLElement | null)?.blur(); // Focus initial element if focused outside. - const focusedItemIndex = findFocusableIndex(focusableElements, event.target); + const focusedItemIndex = findFocusableIndex(focusableElements, target); if (focusedItemIndex === -1) return focusableElements[0].focus(); }, [getFocusableElements, locked],