diff --git a/packages/react/src/components/ComposedModal/ComposedModal.tsx b/packages/react/src/components/ComposedModal/ComposedModal.tsx index dfc111add56c..96a47deacbc4 100644 --- a/packages/react/src/components/ComposedModal/ComposedModal.tsx +++ b/packages/react/src/components/ComposedModal/ComposedModal.tsx @@ -305,28 +305,30 @@ const ComposedModal = React.forwardRef( }); useEffect(() => { - const focusButton = (focusContainerElement) => { - if (focusContainerElement) { - const primaryFocusElement = - focusContainerElement.querySelector(selectorPrimaryFocus); - if (primaryFocusElement) { - primaryFocusElement.focus(); - return; - } - if (button.current) { - button.current.focus(); - } + const initialFocus = (focusContainerElement) => { + const containerElement = focusContainerElement || innerModal.current; + const primaryFocusElement = containerElement + ? containerElement.querySelector(selectorPrimaryFocus) + : null; + + if (primaryFocusElement) { + return primaryFocusElement; } + + return button && button.current; }; - if (!open) { - return; - } + const focusButton = (focusContainerElement) => { + const target = initialFocus(focusContainerElement); + if (target) { + target.focus(); + } + }; - if (innerModal.current) { + if (open && isOpen) { focusButton(innerModal.current); } - }, [open, selectorPrimaryFocus]); + }, [open, selectorPrimaryFocus, isOpen]); return (
( aria-label={ariaLabel ? ariaLabel : generatedAriaLabel} aria-labelledby={ariaLabelledBy}> {/* Non-translatable: Focus-wrap code makes this `