From fb33fedb42603dac95c43c793fe9a4b11e5be9ea Mon Sep 17 00:00:00 2001 From: Kate Travers <8152930+ktravers@users.noreply.github.com> Date: Fri, 31 Jan 2025 12:32:40 -0500 Subject: [PATCH] only prevent focus when component is open Otherwise, prevents focus from returning to given returnFocusRef. --- packages/react/src/hooks/useOpenAndCloseFocus.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/react/src/hooks/useOpenAndCloseFocus.ts b/packages/react/src/hooks/useOpenAndCloseFocus.ts index ca5d15d68c9..a5dd2f7962d 100644 --- a/packages/react/src/hooks/useOpenAndCloseFocus.ts +++ b/packages/react/src/hooks/useOpenAndCloseFocus.ts @@ -16,18 +16,25 @@ export function useOpenAndCloseFocus({ preventFocusOnOpen, }: UseOpenAndCloseFocusSettings): void { useEffect(() => { - if (preventFocusOnOpen) { + const isOpen = containerRef.current || initialFocusRef?.current + + // Do nothing if component is open and focus should be prevented on open + if (isOpen && preventFocusOnOpen) { return } - const returnRef = returnFocusRef.current + + // If initial focus ref is given and present, apply focus if (initialFocusRef && initialFocusRef.current) { initialFocusRef.current.focus() + // If container ref is present, apply focus } else if (containerRef.current) { const firstItem = iterateFocusableElements(containerRef.current).next().value firstItem?.focus() } + + // Else, component is closed, and focus should be applied to given returnFocusRef element return function () { - returnRef?.focus() + returnFocusRef.current?.focus() } }, [initialFocusRef, returnFocusRef, containerRef, preventFocusOnOpen]) }