Dialog with Next.js App Router
Using Next.js Parallel Routes to create an accessible modal Dialog that is rendered on the server and controlled by the URL, with built-in focus management.
Components
Controlling the Dialog state
To control the open state, you can pass the open
and onClose
props to the Dialog
component. These props allow you to synchronize the dialog state with other state sources, such as the browser history.
Restoring focus on hide
When the dialog is closed, the focus is automatically returned to the element that was previously focused before opening the dialog. Typically, this is the element that triggered the dialog. However, in cases where a user navigates to the modal URL directly, there is no element to focus on hide.
To handle this scenario, the autoFocusOnHide
prop can be used to specify a fallback element to focus on hide:
const pathname = usePathname();
if (!element) {
document.querySelector(`[href="${pathname}"]`)?.focus();
}
return true;
}}
>