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]) }