Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 50 ยท Production Concerns

Modal Routes and Background Locations

Give a modal its own URL: open it over the current page with a background location, deep-link to it, close it with the back button, and compare nested-route modals.

A photo grid opens each picture in a modal. It feels great until someone copies the address bar: the URL says /photos, so the link you send a friend shows the grid, not the picture. Press the back button and you leave the whole gallery instead of closing the modal. Refresh, and the modal is gone.

The fix is to treat the modal as a route: opening a photo changes the URL to /photo/2, closing it goes back, and the same URL works as a shared link. The hard part is that you want two different things from one URL. When the visitor clicks inside the app, /photo/2 should appear over the gallery. When someone arrives at /photo/2 directly, it should be a full page. In this lesson you will see the two standard ways to build this with React Router and a way to choose between them. You should know Link and NavLink and useLocation and Navigation State first.

The background location pattern

The trick uses location state: a value you can attach to a navigation. A <Link> that opens the modal also says "remember where I came from". The app reads that value on every render and, when it exists, renders two route trees: the old page behind the modal (using the remembered location) and the modal for the real URL.

Here is the real React Router code. It is read-only because the live editor cannot install packages:

JSX
// App.jsx - React Router (read-only)
import { Routes, Route, Link, useLocation } from 'react-router';

export default function App() {
  const location = useLocation();
  const background = location.state?.backgroundLocation;

  return (
    <>
      <Routes location={background || location}>
        <Route path="/" element={<Gallery />} />
        <Route path="photo/:id" element={<PhotoPage />} />
      </Routes>

      {background && (
        <Routes>
          <Route path="photo/:id" element={<PhotoModal />} />
        </Routes>
      )}
    </>
  );
}

function Gallery() {
  const location = useLocation();
  return photos.map((photo) => (
    <Link
      key={photo.id}
      to={`/photo/${photo.id}`}
      state={{ backgroundLocation: location }}
      preventScrollReset
    >
      <img src={photo.thumb} alt={photo.title} />
    </Link>
  ));
}

The location prop of <Routes> is the key. Normally <Routes> matches against the browser's current location. When you pass a different location, it matches against that one instead, so the first <Routes> keeps rendering the gallery even though the address bar says /photo/2. The second <Routes> only exists while a background is set, and it always uses the real location, so it renders the modal.

There are two entry points to the same URL:

flowchart TD
    A["Click a photo in the app<br/>Link with state"] --> B["URL /photo/2<br/>state.backgroundLocation = /"]
    C["Open /photo/2 directly<br/>shared link, new tab, crawler"] --> D["URL /photo/2<br/>no state"]
    B --> E["Routes #1 (location = background)<br/>renders Gallery"]
    B --> F["Routes #2 (real location)<br/>renders PhotoModal"]
    D --> G["Routes #1 (real location)<br/>renders PhotoPage, a full page"]

One URL, two presentations: the navigation state decides whether the page is shown as a modal or as a full page.

Two small props make the experience better. state carries the background. preventScrollReset stops React Router from scrolling the page to the top when the URL changes (see Scroll Restoration, Focus and Page Titles), which would otherwise throw away the visitor's position in the grid.

Real library or stand-in? The code above is the real API. The live examples below use a small hand-written router built on React and location.hash. It has its own useLocation() and Link, and it keeps the navigation state in memory next to the hash, because the sandboxed preview cannot use the History API. In a real browser, state lives in the history entry, so it also survives a page reload. In the stand-in, state belongs to the navigation that created it: pressing the browser's back button, or loading the URL fresh, gives you a location without state, exactly like opening a shared link. The hash idea itself is explained in Client-Side Routing.

A photo modal over the gallery

Click "Lagoon": the URL becomes #/photo/2, the state line shows background /, and the modal appears over the still-rendered gallery. "Next" and "Previous" change the URL again but pass the same state along, so the background does not change. "Close" goes back to the background location. Press Escape and the same thing happens.

A modal route is only as good as the way it opens and closes. A few rules save you from the usual bugs:

  • Always render a valid full page for the URL without state. A visitor, a search engine or a link preview will never have your navigation state. If /photo/2 shows nothing without a background, you built a modal, not a modal route.
  • Close by going back, when you can. Closing with navigate(-1) makes the back button and the Close button behave the same. But if the visitor started on /photo/2 (a shared link), -1 may leave your site. React Router gives the first entry of a session the location key "default". When location.key === 'default', there is nothing to go back to inside your app, so navigate to a sensible parent such as / instead.
  • Replace when moving between modals. Next and Previous should not each add a history entry, or Close would need several back presses (the stand-in pushes entries to stay simple). In real React Router you write <Link to="..." state={location.state} replace>.
  • Pass the state along. Forgetting state={location.state} on the Next link is the classic bug: the next photo suddenly opens as a full page.
JSX
// PhotoModal.jsx - React Router (read-only)
import { useLocation, useNavigate } from 'react-router';

function PhotoModal() {
  const location = useLocation();
  const navigate = useNavigate();

  function close() {
    if (location.key !== 'default') {
      navigate(-1);
    } else {
      navigate('/', { replace: true });
    }
  }
  // ...render the dialog with a Close button that calls close()
}

With the background pattern and replacing links, -1 always returns to the gallery, because the modal-to-modal moves replaced each other.

The nested-route alternative

There is a simpler design that needs no navigation state: make the modal a child route of the gallery. The gallery is the parent route and renders an Outlet; /photos shows the grid, and /photos/2 shows the grid plus the modal in the outlet.

JSX
// router.jsx - React Router (read-only)
import { createBrowserRouter, Outlet, useLoaderData } from 'react-router';

const router = createBrowserRouter([
  {
    path: '/photos',
    loader: photosLoader,
    element: <GalleryWithModal />,
    children: [{ path: ':id', loader: photoLoader, element: <PhotoModal /> }],
  },
]);

function GalleryWithModal() {
  const photos = useLoaderData();
  return (
    <>
      <Gallery photos={photos} />
      <Outlet />
    </>
  );
}

This works in data mode and framework mode, and the modal gets its own loader. The difference is what a deep link shows: the gallery appears behind the modal even for a shared link, and there is no separate full-page version. That is often perfectly fine (a modal over a list is the whole design), and it avoids the "two route trees" trick. Because the gallery is the same parent route in both URLs, its component stays mounted when the modal opens, so its state survives. Try it: click Like, then open a photo.

A modal as a child route of the gallery

Press "Like" twice, open "Forest", then close it: the counter still says 2, because the gallery route is the parent of both URLs and never unmounts. In the previous example the same effect came from rendering the gallery for the background location.

Accessibility and polish

A modal route still has to behave like a modal:

  • Give the container role="dialog" (or use the native <dialog> element with showModal()), aria-modal="true" and an accessible name.
  • Move focus into the dialog when it opens, and return focus to the link that opened it when it closes.
  • Close on Escape, and keep keyboard focus from wandering behind the dialog.
  • Stop the page behind from scrolling (overflow: hidden on the body while open) without resetting its scroll position.
  • Set a good document title for the URL; deep-linked modals are real pages for search engines and sharing.

Which pattern should you choose?

You need Use
The same URL to be a modal inside the app and a full page when opened directly Background location (state)
One fixed list behind the modal, with the modal's own loader Nested child route with an Outlet
A modal that does not need a URL at all (a confirm box) Plain component state

The data-router variants rely on loaders, which you met in Loaders: Data Before Render. The URL-driven approach is the same idea as Putting UI State in the URL.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the background location pattern, how does the app know that /photo/2 should appear as a modal over the gallery?

    The clicked Link attaches the current location as state. The app checks location.state?.backgroundLocation: if it exists, it renders the modal over that location; if not, it renders the URL as a normal page.
  2. 2. What does the location prop on <Routes> do in this pattern?

    Passing background || location lets the first <Routes> keep rendering the gallery even though the real URL has already changed to /photo/2.
  3. 3. Someone opens a shared link to /photo/2 in a new tab. What should they see with the background location pattern?

    Without state there is no background, so the first <Routes> matches the real URL. That is why the full-page route for /photo/:id must exist.
  4. 4. You build the modal as a child route of /photos with an Outlet. What is true when you open /photos/2 directly?

    A child route always renders inside its parent's Outlet, so the parent route's component (the gallery) is part of every URL below it, including deep links.
  5. 5. Why does a Close button that always calls navigate(-1) sometimes misbehave?

    A deep-linked visit has no earlier entry inside your app. Check whether location.key is 'default' (the first entry) and navigate to a parent route instead.

Summary

  • A modal route gives a modal its own URL, so links, the back button and refresh all work.
  • Background location: pass state={{ backgroundLocation: location }} from the link, render <Routes location={background || location}>, and render the modal in a second <Routes> while a background exists.
  • Always provide a full-page route for the same URL, because shared links and crawlers arrive without state.
  • Close with navigate(-1) only when the visitor came from inside the app (location.key !== 'default'), and use replace when moving between modals.
  • A child route with an Outlet is a simpler alternative, at the price of always showing the parent behind the modal.
  • Treat it as a real dialog: role, focus, Escape, and no scroll jump (preventScrollReset).

Next: Authentication with Loaders and Actions