日本語

How to Make a Back Button to the Previous Page in React Router

​​React​React Router,TypeScript,Vite

To make a back button to the previous page in React Router, pass -1 to the function returned by useNavigate(). However, if someone opens a detail page directly from an external site or a search result and presses this button, they will be sent to a page outside the app. This is how to add a "Back" button to a product or blog post detail page so that it returns to the list.

In my test environment, I pressed "Back" both after moving from a list to a detail page and after opening the detail URL directly, and checked which page it went to.

Note

The test environment was Ubuntu 24.04 and Node.js 22.23.4. I installed React Router 8.5.1 in a project created with the react-ts template of npm create vite@latest (React 19.3.1, Vite 8.3.8, TypeScript 7.0.2), and wrapped the components in StrictMode for testing. I opened the pages with Chromium 153 controlled by Playwright 1.63.0, and performed the browser's back action with Playwright's page.goBack(). I did not test React Router's framework mode, browsers other than Chromium, or the behavior of a production build.

Going back one entry in history with navigate(-1)

In the button's onClick, pass -1 to the function returned by useNavigate().

tsx
// BackButton.tsx
import { useNavigate } from 'react-router';

// A button that goes back one entry in the history
export function BackButton() {
  const navigate = useNavigate();
  return (
    <button type="button" onClick={() => navigate(-1)}>
      戻る
    </button>
  );
}

The useNavigate reference states that passing a number moves backward or forward in the history stack, and includes an example that goes back with -1. In the useNavigate implementation (hooks.tsx), when a number is passed, it moves through the history by that number as is.

For the test, I created a cat list page and a detail page as follows, and placed this button on the detail page.

tsx
// pages.tsx (excerpt)
import type { ReactNode } from 'react';
import { Link, useParams } from 'react-router';

export function CatList() {
  return (
    <>
      <h1>猫の一覧</h1>
      <ul>
        <li>
          <Link to="/cats/1">猫の1番</Link>
        </li>
        <li>
          <Link to="/cats/3">猫の3番</Link>
        </li>
      </ul>
    </>
  );
}

export function CatDetail({ back }: { back: ReactNode }) {
  const { catId } = useParams();
  return (
    <>
      <h1>猫の{catId}番</h1>
      {back}
    </>
  );
}

pages.tsx also contains a Layout that renders a header. There is also a line that logs location.key to the console for testing, but I have omitted it above.

I wrote the routes in declarative mode with <Routes> as follows. The list and detail routes sit under a Layout route that has no path. I pass <BackButton /> as back.

tsx
// decl.tsx (excerpt)
function AppRoutes({ back }: { back: ReactNode }) {
  return (
    <Routes>
      <Route element={<Layout />}>
        <Route path="/" element={<CatList />} />
        <Route path="/cats/:catId" element={<CatDetail back={back} />} />
      </Route>
    </Routes>
  );
}

I opened the list, pressed the link to "Cat 3", and then pressed "Back" on the detail page, which returned me to the list page.

I also reloaded the browser on the detail page and then pressed "Back", which also returned me to the list.

Opened directly from an external site, it goes back outside the app

The problem occurs when there is no earlier entry inside the app. I put an "external page" on a different origin (in the test, a server on a different port number) and opened the detail page by clicking a link there. Pressing "Back" on this detail page with BackButton returned me to the external page, not to the app's list.

When I opened the detail URL directly in a new tab, it also did not return to the app's list. A new tab in Playwright starts with an empty page (about:blank), so in the test, pressing "Back" moved to about:blank.

The useNavigate reference also notes a caution about moving with a number such as navigate(-1). If the page with the back button can be the first page opened in the app, there may be no earlier history entry, or the move may go somewhere unexpected, such as a different domain. For this reason, it says to use it only when you are sure there is a previous entry in the history.

If location.key is "default", move to the list

Whether there is an earlier entry inside the app can be determined from the key of the location returned by useLocation(). The description of the Location type states that the key of the location for the first page opened is always "default".

In the test as well, location.key was "default" when I opened the detail page from an external page or opened it directly. When I came from the list, it was a string such as bv1m1wka.

So when key is "default", I make the button move to a predetermined page instead of using navigate(-1).

tsx
// SafeBackButton.tsx
import { useLocation, useNavigate } from 'react-router';

type Props = {
  // The path to move to when there is no earlier entry inside the app
  fallback: string;
  // If true, replace the current history entry when moving to fallback
  replace?: boolean;
};

// If there is no earlier entry inside the app, a button that moves to fallback
export function SafeBackButton({ fallback, replace = false }: Props) {
  const navigate = useNavigate();
  const location = useLocation();
  // On the first page opened, location.key is "default"
  const canGoBack = location.key !== 'default';

  return (
    <button
      type="button"
      onClick={() => {
        if (canGoBack) {
          navigate(-1);
        } else {
          navigate(fallback, { replace });
        }
      }}
    >
      戻る
    </button>
  );
}

I placed <SafeBackButton fallback="/" /> on the detail page and performed the same actions as with BackButton.

How the detail page was opened "Back" with BackButton "Back" with SafeBackButton
Pressed the link to "Cat 3" in the list List List
Reloaded the detail page after moving from the list List List
Opened from a link on an external page External page List
Opened directly in a new tab about:blank (Playwright's new tab) List

When I came from the list, it went back one entry in history as before. Even after reloading the detail page, key was not "default", and navigate(-1) returned me to the list. Only when I opened the page from a link on an external page, or directly in a new tab, did it move to the list at fallback.

A diagram of the history when "Cat 3" is opened from a link on an external page. In the top row, with a button that only uses navigate(-1), pressing "Back" goes from "Cat 3" (key is "default") back to the "External page" on the left. In the bottom row, with a button that moves to the list when key is "default", it goes from "Cat 3" down to "Cat list"
Where the two buttons’ Back go from a detail page opened from an external page

I also tried the same SafeBackButton in data mode, which uses createBrowserRouter and <RouterProvider>. When moving from the list, after a reload, and when opened directly, the results were the same as in declarative mode.

The browser's "Back" after moving to the list changes with replace

When SafeBackButton moves to the list, whether you add replace changes where the browser's "Back" goes afterward.

Without replace, the list is pushed as a new history entry. When I opened the detail page from an external page, moved to the list with SafeBackButton, and then pressed the browser's "Back", it returned to the detail page.

With replace, as in <SafeBackButton fallback="/" replace />, the detail page's history entry is replaced by the list. When I pressed the browser's "Back" after the same actions, it returned to the external page. As described in the useNavigate reference, replace is an option that replaces the current history entry with the new one.

Choose based on whether you want the browser's "Back" to let users see the detail page again, or to return them to the site they came from.

For a parent page link, Link to=".." also works

If you only want to always move to a parent page such as the list, rather than going "back", you can write it with <Link to="..">.

tsx
<CatDetail back={<Link to="..">一覧へ</Link>} />

As described in the relative section of the <Link> reference, .. by default goes up to the parent based on the route hierarchy. Layout routes without a path are not counted. In my test routes, the parent of /cats/:catId was /, and the link's href was also the list path. Even when I opened the detail page directly, this link moved me to the list.

However, this is not going back through history but a new move to the list. When I moved from the list to a detail page, pressed the "Go to list" link, and then pressed the browser's "Back", it returned to the detail page. It does not return to the page that was open before the list. Use SafeBackButton when you want back-navigation that follows the path the user came by, and <Link to=".."> when the destination should always be the same.

​Posted by 86