Category: Next.js, React and TypeScript

React: Modal Loses Keyboard Focus

Read this guide in Polish

When the Tab dialog is opened, it goes to items under modal, and Escape does not close the window. The transfer of a DOM through createPortal does not automatically provide a full mechanism for the availability of dialogue.

How to identify the source of the problem

Check the role of dialogue, aria-modal, label and focus order after opening. Check whether you can still activate the elements in the background by keyboard or if the focus disappears after closing.

Compare the message from the console with the result of the production compilation and the condition after the page has been refreshed.

Repair steps

Use native dialogue or library to provide focus trap, Escape support and proper focus return. Lock background interaction during modal dialogue, and when closed, set focus to the opening button.

How to Test Solution

Navigation Tab remains in the open modal window, and Escape closes it and returns focus.

Security and restrictions

Do not treat high z-index alone as ensuring the availability of a modal interface.