Skip to content

If Back Should Close It, Your Modal Is a Route

A photo in a gallery that opens with useState has no address, so Back skips it and a shared link shows the grid. How I build those modals with TanStack Router, Next.js and Expo Router, and why Next.js needs a catch-all route to close one.

9 min read

All writing

You open a photo in a gallery, press Back, and land on the search results you came from. The photo had no address of its own: a component flipped open to true and drew it over the grid. Refresh and it's gone. Copy the address to send it to a friend and they get the grid.

Both windows below show the same gallery. The Boolean window opens its photo with useState; the Route window gives it a route that happens to look like a modal. Open a photo in each, then try the buttons under them.

trailnotes.example/gallery
Trail notesAll photos
  1. search
  2. /gallery

Open a photo. This window keeps it open with a boolean.

trailnotes.example/gallery
Trail notesAll photos
  1. search
  2. /gallery

Open a photo. This window gives each one an address, such as /photos/42.

Back, Refresh and the new tab act on both windows at once. The strip under each window is its history.

If a visitor would expect Back, a refresh or a shared link to remember it, it's navigation, and it gets a route. A tooltip or a "delete this?" confirmation stays state, because nobody links to one.

Moving the boolean into a store makes it worse

Lifting open into a parent, or into Zustand or Redux once distant components need to open the same photo, lets any of them open it. Back still skips it, and a deep link arrives to an empty store.

Then someone wants the photo to be shareable, so the store starts pushing /photos/42 itself. Press Back: the address returns to /gallery while the store, which only half-listens to popstate, still renders the photo. Keep the cart and drafts in Zustand; whether the photo is open belongs to the router.

Close depends on how the visitor got there

Opened from the gallery, /photos/42 sits on top of a gallery that is already mounted. Followed in from a deep link that launched the app cold, it has nothing under it, so the app builds the gallery tab (top of the grid, no filter) and puts the photo over that. Pasted into a new tab, there is nothing to build on, and the photo is the page.

trailnotes.example/photos/42
Trail notesStorms
After the storm
North basin, 14 Aug
Underneath
The gallery the visitor was browsing, still mounted: the Storms filter on, a row scrolled down.
In TanStack Router, Close calls
router.history.back()

Close the photo in each tab, or press All photos on its own page, to see what's underneath and which call gets you there.

Calling back() everywhere is the tempting shortcut. On a pasted link the previous entry might be Google, or nothing at all if the app launched cold, so a standalone photo needs a named destination.

When it closes to the gallery, you can push the gallery as a new entry, so Back reopens the photo, or replace the photo's entry, so it's gone. The demo pushes. Replace instead if Back shouldn't bring back what the visitor just closed.

Where the photo appears is presentation, and it can change without touching any of this. A dialog on a wide screen and a bottom sheet on a phone can be one route with one set of rules for closing.

A gallery that never unmounted still has its scroll position, its Storms filter and the tile that should get the focus back, without any code of yours. The trap is code that restores or resets that state on every arrival at /gallery. Restore scroll there and a visitor who opened the gallery from the header lands halfway down the grid; carry the filter over and a direct visit to /photos/42 inherits one because the same path was once an overlay. Only touch that state when the navigation says the visitor is leaving the overlay.

RouterOpened in contextOpened directlyClose
TanStack RouterRender the photo as a child of the gallery, show a masked URLThe URL resolves as a normal routeBack, or navigate to a fallback
Next.jsIntercept the client navigation into a parallel slotThe canonical page rendersBack from the slot, ordinary navigation from the page
Expo RouterPresent the screen over the current stackBuild the anchor screen first, then presentDismiss to whatever is underneath

TanStack Router: one history entry, two locations

TanStack Router has the cleanest model of the three, because with route masking the route the app renders and the URL people see are an explicit pair.

For the photo, the overlay is a child of the gallery route, so the gallery stays mounted and renders it through its <Outlet />. Gallery tiles link to /gallery/photos/$photoId. The standalone /photos/$photoId is a route of its own, and a mask, passed to the router, pairs the two:

tsx
const photoModalMask = createRouteMask({
  routeTree,
  from: "/gallery/photos/$photoId",
  to: "/photos/$photoId",
  params: true,
  unmaskOnReload: true,
});

const router = createRouter({ routeTree, routeMasks: [photoModalMask] });

from is what the app renders. to is what the address bar shows and what people share. I read the router's source to see how the pair survives: it writes the to URL to the browser's history and tucks the real location into that entry's history.state, under __tempLocation.

A shared URL never carries history state, so a new tab always gets the plain /photos/42. A reload in the same tab keeps history.state, so by default the mask comes back too. unmaskOnReload: true stamps the entry with a key that belongs to the current page load; after a reload the key no longer matches, the router ignores the stored location, and the visible URL resolves as a direct visit.

The contact form on this site is masked too, and you can try it: press Start a project in the header. The address becomes /contact while this post stays exactly where it is, and Back closes it. From 768px up it's a dialog, and below that a bottom sheet, on the same route. It uses a different technique from the photo because it opens over any page, so there's no single parent route to nest it under. The link behind that button:

tsx
<Link
  mask={{ to: "/contact", unmaskOnReload: true }}
  resetScroll={false}
  state={(previous) => ({
    ...previous,
    contactFocus,
    contactOverlay: true,
  })}
  to="."
/>

to="." keeps the current page as the real destination, so opening the overlay doesn't render the /contact route component or run its loader. The overlay itself lives in the root layout and watches contactOverlay in the history state. Custom history fields need a type before you can read them:

tsx
declare module "@tanstack/history" {
  interface HistoryState {
    contactFocus?: ContactFocus;
    contactOverlay?: boolean;
  }
}

As with the photo, a reload drops the mask, so /contact resolves as its own route. The layout tells the two apart in one line each:

tsx
const masked = location.state.contactOverlay === true;
const coldStart = location.pathname === "/contact" && !masked;

When it's masked, closing goes back. On a cold start there's no page behind it to go back to, so closing navigates to Home as a new entry, which is also what renders behind the form. Back from there brings the form back.

Next.js: put the photo in a parallel slot

text
app/
  @photo/
    (.)photos/[id]/page.tsx
    [...catchAll]/page.tsx
    default.tsx
  gallery/page.tsx
  photos/[id]/page.tsx
  layout.tsx

(.)photos/[id] intercepts client-side navigation to a photo and renders it in the @photo slot, while children keeps showing the gallery. That folder alone renders nothing, though: the root layout.tsx has to accept photo as a prop and render it next to children. A direct request skips the interception and gets photos/[id]/page.tsx.

default.tsx and [...catchAll]/page.tsx are both one line:

tsx
export default function Empty() {
  return null;
}

Leave out [...catchAll] and the photo stays on screen after you navigate away: during client navigation a slot keeps showing its last page even when the new URL doesn't match it, so the slot needs a route that matches everything else and renders nothing. default.tsx is what the slot renders on a hard navigation, when, in the docs' words, Next.js "cannot recover a slot's active state".

Keep the interceptor as narrow as photos/[id]. A broad dynamic interceptor near the root can also catch unrelated sibling routes during client navigation, and getting out is awkward: returning null from the interceptor leaves the slot empty instead of handing the page back to children, and redirecting to the same visible URL can land in the interceptor again. Even the narrow version spreads one modal across five files that anyone adding a sibling route has to know about.

The photo lives at app/photos/[id].tsx, next to the (tabs) group that holds the gallery, and the root stack presents it over whichever screen is showing:

app/_layout.tsx
export const unstable_settings = { anchor: "(tabs)" };

export default function RootLayout() {
  return (
    <Stack>
      <Stack.Screen name="(tabs)" />
      <Stack.Screen
        name="photos/[id]"
        options={{ presentation: "transparentModal" }}
      />
    </Stack>
  );
}

transparentModal keeps the previous screen visible while the photo route draws its own sheet and backdrop. The anchor is the base Expo puts under a deep link; without one, the docs warn, "the screen behind the modal will be wiped away, leaving no navigation context."

Because the app built that base itself, closing doesn't have to guess at history. router.dismiss() pops the photo off the root stack, and what's revealed is the gallery tab, whether the visitor tapped in from it or arrived cold.

Test the cold start, the reload and Back before merging

  1. Open the URL in a fresh tab and launch the app cold from its deep link. Each renders the photo as a page or over a base you built.
  2. Reload while the overlay is open, then press Back.
  3. Switch between dialog, sheet and full screen, and check that Back behaves the same in each.
  4. Navigate away from the overlay. Any parallel slot clears.

Keep reading.

Other problems I ran into on the job, and what fixed them.

Browse all writing

Engineering beyond the ordinary.

Start a project