MemoryRouter

<MemoryRouter>

Type declaration
declare function MemoryRouter(
  props: MemoryRouterProps
): React.ReactElement;

interface MemoryRouterProps {
  basename?: string;
  children?: React.ReactNode;
  initialEntries?: InitialEntry[];
  initialIndex?: number;
  future?: FutureConfig;
}

A <MemoryRouter> stores its locations internally in an array. Unlike <BrowserHistory> and <HashHistory>, it isn't tied to an external source, like the history stack in a browser. This makes it ideal for scenarios where you need complete control over the history stack, like testing.

  • <MemoryRouter initialEntries> defaults to ["/"] (a single entry at the root / URL)
  • <MemoryRouter initialIndex> defaults to the last index of initialEntries

Tip:

Most of React Router's tests are written using a <MemoryRouter> as the source of truth, so you can see some great examples of using it by just browsing through our tests.

import * as React from "react";
import { create } from "react-test-renderer";
import {
  MemoryRouter,
  Routes,
  Route,
} from "react-router-dom";

describe("My app", () => {
  it("renders correctly", () => {
    let renderer = create(
      <MemoryRouter initialEntries={["/users/mjackson"]}>
        <Routes>
          <Route path="users" element={<Users />}>
            <Route path=":id" element={<UserProfile />} />
          </Route>
        </Routes>
      </MemoryRouter>
    );

    expect(renderer.toJSON()).toMatchSnapshot();
  });
});

basename

Configure your application to run underneath a specific basename in the URL:

function App() {
  return (
    <MemoryRouter basename="/app">
      <Routes>
        <Route path="/" /> {/* 👈 Renders at /app/ */}
      </Routes>
    </MemoryRouter>
  );
}

future

An optional set of Future Flags to enable. We recommend opting into newly released future flags sooner rather than later to ease your eventual migration to v7.

function App() {
  return (
    <MemoryRouter future={{ v7_startTransition: true }}>
      <Routes>{/*...*/}</Routes>
    </MemoryRouter>
  );
}
Docs and examples CC 4.0