日本語

How to Make React Tabs Work with the Browser Back Button Using the URL Hash

​​React​hashchange,Playwright,tabs,TypeScript,useSyncExternalStore

If you read the selected tab from the URL hash (such as #specs) instead of React state, each tab press adds one history entry, and the browser's Back button returns to the previous tab. The same approach also works when you want to share a URL that opens a specific tab, or to open a specific tab from a link on the page. This applies to tabs such as "Overview, Specs, Reviews" on a product page, or tabs in a settings screen.

Note

I tested this on Ubuntu 24.04 with Node.js 22.23, React 19.3.1, TypeScript 7.0, and Chromium 153 from Playwright 1.63. The development build from esbuild ran in StrictMode. I used Playwright's page.goBack() and page.goForward() to press the browser's Back and Forward buttons. I did not test Firefox, Safari, real phones, combinations with routing libraries such as React Router or Next.js, or server-side rendering (SSR).

The following GIF shows two tab presses followed by two presses of the browser's Back button. The band at the bottom shows the URL at each step (the file name and the hash). The labels in the GIF are in Japanese.

On a product page, pressing the tabs Specs and then Reviews changes the URL to index.html#specs and then index.html#reviews. Pressing the browser's Back button returns to the Specs tab and #specs. Pressing it again returns to the URL without a hash and the Overview tab. The labels in the image are in Japanese.
The movement of the tabs and the URL when pressing the Specs tab, then the Reviews tab, and then the browser’s Back button twice. The bands at the top and bottom, the ← Back frame (labels in Japanese), and the cursor were added to the test page for illustration.

A hook that reads the hash and re-renders on hashchange

The hook does not store the selected tab in state. Instead, it reads location.hash every time. When the hash changes, a hashchange event is sent to window, and the hook subscribes to it with useSyncExternalStore. The official reference shows this pattern, which reads a browser value and combines it with an event that reports changes, using navigator.onLine as the example.

ts
// src/useHashTab.ts
import { useCallback, useSyncExternalStore } from 'react';

// Be notified when the URL hash changes (including Back and Forward)
function subscribe(onChange: () => void) {
  window.addEventListener('hashchange', onChange);
  return () => window.removeEventListener('hashchange', onChange);
}

function getHash() {
  return window.location.hash;
}

// When rendering HTML on the server there is no hash, so treat it as empty
function getServerHash() {
  return '';
}

export function useHashTab<T extends string>(ids: readonly T[], fallback: T) {
  const hash = useSyncExternalStore(subscribe, getHash, getServerHash);
  // For an unknown hash (such as #unknown), show the fallback tab
  const current = ids.find((id) => `#${id}` === hash) ?? fallback;

  const select = useCallback((id: T, options?: { replace?: boolean }) => {
    if (options?.replace) {
      // Rewrite only the hash of the current entry without adding a history entry
      window.location.replace(`#${id}`);
    } else {
      // Push one history entry. Nothing is pushed if the hash is the same
      window.location.hash = id;
    }
  }, []);

  return [current, select] as const;
}

subscribe is defined outside the component because, if a new function is passed on every render, React resubscribes each time (troubleshooting section of the official reference).

To switch tabs, the hook assigns to location.hash. I did not use history.pushState() to change the hash, because MDN notes that changing the hash with pushState() does not fire hashchange.

When there is no hash, or the value is unknown, such as #unknown, the hook shows the tab passed as fallback. In my test environment, opening index.html#unknown produced no error, and the Overview tab was displayed.

Calling select from the tab component

The tab component uses current from useHashTab to decide which tab is selected, and calls select on click. I added role, aria-selected, aria-controls, and aria-labelledby following the WAI-ARIA Authoring Practices tabs pattern.

tsx
// src/ProductTabs.tsx
import { useRef, type KeyboardEvent } from 'react';
import { useHashTab } from './useHashTab';

const tabs = [
  { id: 'overview', label: '概要' },
  { id: 'specs', label: '仕様' },
  { id: 'reviews', label: 'レビュー' },
] as const;
type TabId = (typeof tabs)[number]['id'];
const ids: TabId[] = tabs.map((tab) => tab.id);

export function ProductTabs() {
  const [current, select] = useHashTab(ids, 'overview');
  const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);

  // When switching with ←→, do not add a history entry on each press
  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
    e.preventDefault();
    const step = e.key === 'ArrowRight' ? 1 : -1;
    const next = (ids.indexOf(current) + step + ids.length) % ids.length;
    select(ids[next], { replace: true });
    tabRefs.current[next]?.focus();
  };

  return (
    <div>
      <div role="tablist" aria-label="商品の情報" onKeyDown={onKeyDown}>
        {tabs.map((tab, i) => (
          <button
            key={tab.id}
            ref={(el) => {
              tabRefs.current[i] = el;
            }}
            type="button"
            role="tab"
            id={`tab-${tab.id}`}
            aria-selected={tab.id === current}
            aria-controls={`panel-${tab.id}`}
            tabIndex={tab.id === current ? 0 : -1}
            onClick={() => select(tab.id)}
          >
            {tab.label}
          </button>
        ))}
      </div>
      {tabs.map((tab) => (
        <div
          key={tab.id}
          role="tabpanel"
          id={`panel-${tab.id}`}
          aria-labelledby={`tab-${tab.id}`}
          hidden={tab.id !== current}
        >
          <PanelBody id={tab.id} />
        </div>
      ))}
    </div>
  );
}

function PanelBody({ id }: { id: TabId }) {
  if (id === 'overview') {
    return (
      <p>
        3本セットのねこじゃらしです。<a href="#reviews">レビューを読む</a>
      </p>
    );
  }
  if (id === 'specs') return <p>長さ:45cm/重さ:30g</p>;
  return <p>★★★★☆ よく遊んでくれます。</p>;
}

I cover keyboard operation (the Home and End keys, and where the Tab key stops) in a separate article, "How to Make React Tabs Switchable with the Keyboard." This article looks only at how the ←→ keys interact with history.

Back and Forward return to the previous tab

I opened this page from a link on a previous page, pressed the tabs, and then pressed Back and Forward. The history.length column shows how many entries were added since the page was first opened.

Operation URL hash Displayed tab History count
Just opened None Overview ±0
Click "Specs" #specs Specs +1
Click "Reviews" #reviews Reviews +2
Click "Reviews" again #reviews Reviews +2 (no change)
Back #specs Specs +2
Back again None Overview +2
Back again (previous page) - +2
Forward None Overview +2
Forward again #specs Specs +2

When I pressed the tab that was already selected, the hash stayed the same, so no history entry was added. Returning to the state with no hash displayed the fallback tab, Overview. On the third Back press, the tab history was used up, and the browser moved to the previous page.

With the ←→ keys, location.replace() avoids adding history entries

To switch tabs with the ←→ keys without adding a history entry for each press, onKeyDown calls select(ids[next], { replace: true }). Inside the hook, this uses location.replace(). When navigation happens with replace(), the URL from before the move (here, the hash) is not kept in history.

I clicked "Specs", then pressed the → key twice and the ← key once.

Operation URL hash Displayed tab History count
Click "Specs" #specs Specs +1
→ key #reviews Reviews +1
→ key (second time) #overview Overview +1
← key #reviews Reviews +1
Back None Overview +1

The keys changed the hash and the tab, but the history count did not increase. The #specs entry had been replaced by #reviews, so one press of Back went to the state with no hash without passing through "Specs". If you remove { replace: true }, the key press behaves like a click and assigns to location.hash.

Page links and URLs with a hash also open the same tab

When you move to the tab from outside with <a href="#reviews">, the hash changes, so hashchange fires and the tab switches. Clicking the "Read reviews" link in the Overview tab opened the Reviews tab, and one history entry was added. Pressing Back returned to Overview.

When you open a URL with a hash directly, the first render reads location.hash, so that tab opens. Opening index.html#reviews displayed the Reviews tab, and it stayed on Reviews after a reload.

The hash part of a URL is not included in requests to the server. It is handled by the browser after it receives the page, as described on MDN's fragment page. This is why the third argument to useSyncExternalStore, getServerHash, returns an empty string. getServerSnapshot is used only during server rendering and hydration of that HTML, and it must return the same value on the server and the client (argument description in the official reference).

Do not give panels an id that matches the hash

In the code in this article, the panel ids are named like panel-specs, which differs from the hash value (specs). If an element has an id that matches the hash, the browser scrolls to that element (MDN's fragment page).

For comparison, I also made a version where the panel ids match the hash, such as specs and reviews. At the top of the page, I placed a 160px-high product description box.

Operation When panel id is panel-○○ When panel id matches the hash
Scroll position when opening a URL with #reviews 0px 244px
Focus after clicking a tab The button of the clicked tab body
After clicking, press → key Switches to the next tab Does not switch

In the version where the id matched the hash, opening a URL with #reviews scrolled the page so that the product description at the top moved out of view. Clicking a tab did not change the scroll position, but focus moved from the clicked tab to body. Pressing the → key afterward did not switch the tab.

​Posted by 86