Skip to content

[fix] Modal: return focus to the trigger when its content takes focus on mount - #2986

Merged
zoontek merged 2 commits into
necolas:masterfrom
miniware9:modal-focus-return-autofocus
Nov 27, 2026
Merged

zoontek merged 2 commits into
necolas:masterfrom
miniware9:modal-focus-return-autofocus

Conversation

@miniware9

Copy link
Copy Markdown
Contributor

Fixes #2985

When a modal closes, ModalFocusTrap refocuses the element that had focus before it opened, which it reads from document.activeElement in a mount effect. If the modal's content takes focus as it mounts, as a TextInput with autoFocus does, React DOM has already focused it by the time the effect runs, so the trap records the input. The input is gone when the modal closes, and focus falls to <body>.

This reads document.activeElement while the trap renders, before its children commit, so the trap records the element that opened the modal. The refocus itself is unchanged.

Test plan

  • I added a unit test, "focus is brought back to the element that triggered modal after closing, when its content took focus on mount". It fails on master, with focus on <body>, and passes with this change. npm run test passes.
  • In the reproduction linked from Modal: focus goes to the body on close when the modal's content took focus on mount #2985 , on react-native-web 0.21.4 with this change applied, in Chrome 157: after the modal opened by Open: field with autoFocus closes, by Escape or by Close, focus is back on that button. Without the change it is on <body>.

@zoontek
zoontek merged commit 1bb0fc7 into necolas:master Nov 27, 2026
5 checks passed
@miniware9
miniware9 deleted the modal-focus-return-autofocus branch November 29, 2026 19:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Modal: focus goes to the body on close when the modal's content took focus on mount

2 participants