MemoryRouter
Edit this pageThe MemoryRouter
can be used to route while keeping the entire routing history within internal memory.
Other routers keep history externally such as in the url like the <HashRouter>
or in the browser history like <Router>
.
Keeping the history in memory is useful when you want full control over the routing history.
Since MemoryRouter
can manipulate MemoryHistory
, it is often used for testing purposes.
In this example, a history object is pre-filled to navigate to the /about
route, which is then passed to the MemoryRouter
.
Manipulating the history
The MemoryHistory
object contains the following methods, which you can use to control the navigation of your app.
- The
get
method retrieves the current route as a string, while theset
method navigates to a new route, allowing for optional parameters like replacing the current history entry or scrolling to a DOM element id. - The
back
andforward
methods mimic the browser's back and forward buttons, respectively, and thego
method navigates a specific number of steps in the history, either backward or forward. - The
listen
method registers a callback to be called on navigation change.
Properties
MemoryHistory
Method | Signature | Description |
---|---|---|
get | get(): string | Returns the current route. |
set | set({ value: string, scroll?: boolean, replace?: boolean }) | Navigates to a new route. value : URL to navigate to. scroll : Scrolls to element by ID (default: false ). replace : Replaces the current history entry (default: false ). |
back | back(): void | Navigates 1 step back in the history. Corresponds to go(-1) . |
forward | forward(): void | Navigates 1 step forward in the history. Corresponds to go(1) . |
go | go(n: number): void | Navigates n steps in the history. Negative for back, positive for forward. Clamped to history length. |
listen | listen(listener: (value: string) => void): () => void | Registers a listener that will be called on navigation. |
MemoryRouter
Property | Type | Description |
---|---|---|
children | JSX.Element , RouteDefinition , or RouteDefinition[] | The route definitions |
root | Component | Top level layout component |
base | string | Base url to use for matching routes |
actionBase | string | Root url for server actions, default: /_server |
preload | boolean | Enables/disables preloads globally, default: true |
explicitLinks | boolean | Disables all anchors being intercepted and instead requires <A> . default: false |
history | MemoryHistory | An optionally pre-filled and mutable history object which will store any navigation events |