Photo Modal with a Real URL
Medium · Navigation
Photo sites like Instagram open a photo in a modal **and** change the URL to /photos/2, while the grid stays visible behind it. The URL can be shared, and Back closes the modal.
In a real Next.js app this uses **intercepting routes** (app/@modal/(.)photos/[id]/page.tsx) together with a parallel route: a click inside the app (soft navigation) shows the modal, while opening the URL directly (or reloading) renders the full app/photos/[id]/page.tsx page. Here we model the idea with one client component that reads usePathname().
Update Gallery:
- Keep the grid of <Link>s to /photos/<id> visible at all times.
- When the pathname is /photos/<id> for a known photo, also render <div role="dialog"> with the photo title in an <h2> and a **Close** button. Unknown ids show no dialog.
- **Close**: if the modal was opened by clicking a photo in the grid, call router.back(), so Close works like the Back button and returns to the exact previous URL (with its query string). If the page was opened directly (e.g. navigate("/photos/2")), there is no previous page in the app, so call router.push("/") instead.
Tip: remember in state that a grid link was clicked (Link accepts an onClick).
Next: error.tsx with Retry