@tanstack/react-router
Version:
Modern and scalable routing for React applications
1,373 lines (996 loc) • 136 kB
JavaScript
export default `# ActiveLinkOptions type
The \`ActiveLinkOptions\` type extends the [\`LinkOptions\`](../LinkOptionsType.md) type and contains additional options that can be used to describe how a link should be styled when it is active.
\`\`\`tsx
type ActiveLinkOptions = LinkOptions & {
activeProps?:
| React.AnchorHTMLAttributes<HTMLAnchorElement>
| (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)
inactiveProps?:
| React.AnchorHTMLAttributes<HTMLAnchorElement>
| (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)
}
\`\`\`
## ActiveLinkOptions properties
The \`ActiveLinkOptions\` object accepts/contains the following properties:
### \`activeProps\`
- \`React.AnchorHTMLAttributes<HTMLAnchorElement>\`
- Optional
- The props that will be applied to the anchor element when the link is active
### \`inactiveProps\`
- Type: \`React.AnchorHTMLAttributes<HTMLAnchorElement>\`
- Optional
- The props that will be applied to the anchor element when the link is inactive
# AsyncRouteComponent type
The \`AsyncRouteComponent\` type is used to describe a code-split route component that can be preloaded using a \`component.preload()\` method.
\`\`\`tsx
type AsyncRouteComponent<TProps> = SyncRouteComponent<TProps> & {
preload?: () => Promise<void>
}
\`\`\`
# FileRoute class
> [!CAUTION]
> This class has been deprecated and will be removed in the next major version of TanStack Router.
> Please use the [\`createFileRoute\`](../createFileRouteFunction.md) function instead.
The \`FileRoute\` class is a factory that can be used to create a file-based route instance. This route instance can then be used to automatically generate a route tree with the \`tsr generate\` and \`tsr watch\` commands.
## \`FileRoute\` constructor
The \`FileRoute\` constructor accepts a single argument: the \`path\` of the file that the route will be generated for.
### Constructor options
- Type: \`string\` literal
- Required, but **automatically inserted and updated by the \`tsr generate\` and \`tsr watch\` commands**.
- The full path of the file that the route will be generated from.
### Constructor returns
- An instance of the \`FileRoute\` class that can be used to create a route.
## \`FileRoute\` methods
The \`FileRoute\` class implements the following method(s):
### \`.createRoute\` method
The \`createRoute\` method is a method that can be used to configure the file route instance. It accepts a single argument: the \`options\` that will be used to configure the file route instance.
#### .createRoute options
- Type: \`Omit<RouteOptions, 'getParentRoute' | 'path' | 'id'>\`
- [\`RouteOptions\`](../RouteOptionsType.md)
- Optional
- The same options that are available to the \`Route\` class, but with the \`getParentRoute\`, \`path\`, and \`id\` options omitted since they are unnecessary for file-based routing.
#### .createRoute returns
A [\`Route\`](../RouteType.md) instance that can be used to configure the route to be inserted into the route-tree.
> ⚠️ Note: For \`tsr generate\` and \`tsr watch\` to work properly, the file route instance must be exported from the file using the \`Route\` identifier.
### Examples
\`\`\`tsx
import { FileRoute } from '@tanstack/react-router'
export const Route = new FileRoute('/').createRoute({
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = Route.useLoaderData()
return <div>{data}</div>
}
\`\`\`
# LinkOptions type
The \`LinkOptions\` type extends the [\`NavigateOptions\`](../NavigateOptionsType.md) type and contains additional options that can be used by TanStack Router when handling actual anchor element attributes.
\`\`\`tsx
type LinkOptions = NavigateOptions & {
target?: HTMLAnchorElement['target']
activeOptions?: ActiveOptions
preload?: false | 'intent'
preloadDelay?: number
disabled?: boolean
}
\`\`\`
## LinkOptions properties
The \`LinkOptions\` object accepts/contains the following properties:
### \`target\`
- Type: \`HTMLAnchorElement['target']\`
- Optional
- The standard anchor tag target attribute
### \`activeOptions\`
- Type: \`ActiveOptions\`
- Optional
- The options that will be used to determine if the link is active
### \`preload\`
- Type: \`false | 'intent' | 'viewport' | 'render'\`
- Optional
- If set, the link's preloading strategy will be set to this value.
- See the [Preloading guide](../../../guide/preloading.md) for more information.
### \`preloadDelay\`
- Type: \`number\`
- Optional
- Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled.
### \`disabled\`
- Type: \`boolean\`
- Optional
- If true, will render the link without the href attribute
# LinkProps type
The \`LinkProps\` type extends the [\`ActiveLinkOptions\`](../ActiveLinkOptionsType.md) and \`React.AnchorHTMLAttributes<HTMLAnchorElement>\` types and contains additional props specific to the \`Link\` component.
\`\`\`tsx
type LinkProps = ActiveLinkOptions &
Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'children'> & {
children?:
| React.ReactNode
| ((state: { isActive: boolean }) => React.ReactNode)
}
\`\`\`
## LinkProps properties
- All of the props from [\`ActiveLinkOptions\`](../ActiveLinkOptionsType.md)
- All of the props from \`React.AnchorHTMLAttributes<HTMLAnchorElement>\`
#### \`children\`
- Type: \`React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode)\`
- Optional
- The children that will be rendered inside of the anchor element. If a function is provided, it will be called with an object that contains the \`isActive\` boolean value that can be used to determine if the link is active.
# MatchRouteOptions type
The \`MatchRouteOptions\` type is used to describe the options that can be used when matching a route.
\`\`\`tsx
interface MatchRouteOptions {
pending?: boolean
caseSensitive?: boolean
includeSearch?: boolean
fuzzy?: boolean
}
\`\`\`
## MatchRouteOptions properties
The \`MatchRouteOptions\` type has the following properties:
### \`pending\` property
- Type: \`boolean\`
- Optional
- If \`true\`, will match against pending location instead of the current location
### \`caseSensitive\` property
- Type: \`boolean\`
- Optional
- If \`true\`, will match against the current location with case sensitivity
### \`includeSearch\` property
- Type: \`boolean\`
- Optional
- If \`true\`, will match against the current location's search params using a deep inclusive check. e.g. \`{ a: 1 }\` will match for a current location of \`{ a: 1, b: 2 }\`
### \`fuzzy\` property
- Type: \`boolean\`
- Optional
- If \`true\`, will match against the current location using a fuzzy match. e.g. \`/posts\` will match for a current location of \`/posts/123\`
# NavigateOptions type
The \`NavigateOptions\` type is used to describe the options that can be used when describing a navigation action in TanStack Router.
\`\`\`tsx
type NavigateOptions = ToOptions & {
replace?: boolean
resetScroll?: boolean
hashScrollIntoView?: boolean | ScrollIntoViewOptions
viewTransition?: boolean | ViewTransitionOptions
ignoreBlocker?: boolean
reloadDocument?: boolean
href?: string
}
\`\`\`
## NavigateOptions properties
The \`NavigateOptions\` object accepts the following properties:
### \`replace\`
- Type: \`boolean\`
- Optional
- Defaults to \`false\`.
- If \`true\`, the location will be committed to the browser history using \`history.replace\` instead of \`history.push\`.
### \`resetScroll\`
- Type: \`boolean\`
- Optional
- Defaults to \`true\` so that the scroll position will be reset to 0,0 after the location is committed to the browser history.
- If \`false\`, the scroll position will not be reset to 0,0 after the location is committed to history.
### \`hashScrollIntoView\`
- Type: \`boolean | ScrollIntoViewOptions\`
- Optional
- Defaults to \`true\` so the element with an id matching the hash will be scrolled into view after the location is committed to history.
- If \`false\`, the element with an id matching the hash will not be scrolled into view after the location is committed to history.
- If an object is provided, it will be passed to the \`scrollIntoView\` method as options.
- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on \`ScrollIntoViewOptions\`.
### \`viewTransition\`
- Type: \`boolean | ViewTransitionOptions\`
- Optional
- Defaults to \`false\`.
- If \`true\`, navigation will be called using \`document.startViewTransition()\`.
- If [\`ViewTransitionOptions\`](../ViewTransitionOptionsType.md), route navigations will be called using \`document.startViewTransition({update, types})\` where \`types\` will be the strings array passed with \`ViewTransitionOptions["types"]\`. If the browser does not support viewTransition types, the navigation will fall back to normal \`document.startTransition()\`, same as if \`true\` was passed.
- If the browser does not support this api, this option will be ignored.
- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.
- See [Google](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types) for more information on viewTransition types
### \`ignoreBlocker\`
- Type: \`boolean\`
- Optional
- Defaults to \`false\`.
- If \`true\`, navigation will ignore any blockers that might prevent it.
### \`reloadDocument\`
- Type: \`boolean\`
- Optional
- Defaults to \`false\`.
- If \`true\`, navigation to a route inside of router will trigger a full page load instead of the traditional SPA navigation.
### \`href\`
- Type: \`string\`
- Optional
- This can be used instead of \`to\` to navigate to a fully built href, e.g. pointing to an external target.
- [\`ToOptions\`](../ToOptionsType.md)
# NotFoundError
The \`NotFoundError\` type is used to represent a not-found error in TanStack Router.
\`\`\`tsx
export type NotFoundError = {
global?: boolean
data?: any
throw?: boolean
routeId?: string
}
\`\`\`
## NotFoundError properties
The \`NotFoundError\` object accepts/contains the following properties:
### \`data\` property
- Type: \`any\`
- Optional
- Custom data that is passed into to \`notFoundComponent\` when the not-found error is handled
### \`global\` property
- Type: \`boolean\`
- Optional - \`default: false\`
- If true, the not-found error will be handled by the \`notFoundComponent\` of the root route instead of bubbling up from the route that threw it. This has the same behavior as importing the root route and calling \`RootRoute.notFound()\`.
### \`route\` property
- Type: \`string\`
- Optional
- The ID of the route that will attempt to handle the not-found error. If the route does not have a \`notFoundComponent\`, the error will bubble up to the parent route (and be handled by the root route if necessary). By default, TanStack Router will attempt to handle the not-found error with the route that threw it.
### \`throw\` property
- Type: \`boolean\`
- Optional - \`default: false\`
- If provided, will throw the not-found object instead of returning it. This can be useful in places where \`throwing\` in a function might cause it to have a return type of \`never\`. In that case, you can use \`notFound({ throw: true })\` to throw the not-found object instead of returning it.
# NotFoundRoute class
> [!CAUTION]
> This class has been deprecated and will be removed in the next major version of TanStack Router.
> Please use the \`notFoundComponent\` route option that is present during route configuration.
> See the [Not Found Errors guide](../../../guide/not-found-errors.md) for more information.
The \`NotFoundRoute\` class extends the \`Route\` class and can be used to create a not found route instance. A not found route instance can be passed to the \`routerOptions.notFoundRoute\` option to configure a default not-found/404 route for every branch of the route tree.
## Constructor options
The \`NotFoundRoute\` constructor accepts an object as its only argument.
- Type:
\`\`\`tsx
Omit<
RouteOptions,
| 'path'
| 'id'
| 'getParentRoute'
| 'caseSensitive'
| 'parseParams'
| 'stringifyParams'
>
\`\`\`
- [RouteOptions](../RouteOptionsType.md)
- Required
- The options that will be used to configure the not found route instance.
## Examples
\`\`\`tsx
import { NotFoundRoute, createRouter } from '@tanstack/react-router'
import { Route as rootRoute } from './routes/__root'
import { routeTree } from './routeTree.gen'
const notFoundRoute = new NotFoundRoute({
getParentRoute: () => rootRoute,
component: () => <div>Not found!!!</div>,
})
const router = createRouter({
routeTree,
notFoundRoute,
})
// ... other code
\`\`\`
# ParsedHistoryState type
The \`ParsedHistoryState\` type represents a parsed state object. Additionally to \`HistoryState\`, it contains the index and the unique key of the route.
\`\`\`tsx
export type ParsedHistoryState = HistoryState & {
key?: string // TODO: Remove in v2 - use __TSR_key instead
__TSR_key?: string
__TSR_index: number
}
\`\`\`
# ParsedLocation type
The \`ParsedLocation\` type represents a parsed location in TanStack Router. It contains a lot of useful information about the current location, including the pathname, search params, hash, location state, and route masking information.
\`\`\`tsx
interface ParsedLocation {
href: string
pathname: string
search: TFullSearchSchema
searchStr: string
state: ParsedHistoryState
hash: string
maskedLocation?: ParsedLocation
unmaskOnReload?: boolean
}
\`\`\`
# Redirect type
The \`Redirect\` type is used to represent a redirect action in TanStack Router.
\`\`\`tsx
export type Redirect = {
statusCode?: number
throw?: any
headers?: HeadersInit
} & NavigateOptions
\`\`\`
- [\`NavigateOptions\`](../NavigateOptionsType.md)
## Redirect properties
The \`Redirect\` object accepts/contains the following properties:
### \`statusCode\` property
- Type: \`number\`
- Optional
- The HTTP status code to use when redirecting
### \`throw\` property
- Type: \`any\`
- Optional
- If provided, will throw the redirect object instead of returning it. This can be useful in places where \`throwing\` in a function might cause it to have a return type of \`never\`. In that case, you can use \`redirect({ throw: true })\` to throw the redirect object instead of returning it.
### \`headers\` property
- Type: \`HeadersInit\`
- Optional
- The HTTP headers to use when redirecting.
# Register type
This type is used to register a route tree with a router instance. Doing so unlocks the full type safety of TanStack Router, including top-level exports from the \`@tanstack/react-router\` package.
\`\`\`tsx
export type Register = {
// router: [Your router type here]
}
\`\`\`
To register a route tree with a router instance, use declaration merging to add the type of your router instance to the Register interface under the \`router\` property:
## Examples
\`\`\`tsx
const router = createRouter({
// ...
})
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}
\`\`\`
# RootRoute class
> [!CAUTION]
> This class has been deprecated and will be removed in the next major version of TanStack Router.
> Please use the [\`createRootRoute\`](../createRootRouteFunction.md) function instead.
The \`RootRoute\` class extends the \`Route\` class and can be used to create a root route instance. A root route instance can then be used to create a route tree.
## \`RootRoute\` constructor
The \`RootRoute\` constructor accepts an object as its only argument.
### Constructor options
The options that will be used to configure the root route instance.
- Type:
\`\`\`tsx
Omit<
RouteOptions,
| 'path'
| 'id'
| 'getParentRoute'
| 'caseSensitive'
| 'parseParams'
| 'stringifyParams'
>
\`\`\`
- [\`RouteOptions\`](../RouteOptionsType.md)
- Optional
## Constructor returns
A new [\`Route\`](../RouteType.md) instance.
## Examples
\`\`\`tsx
import { RootRoute, createRouter, Outlet } from '@tanstack/react-router'
const rootRoute = new RootRoute({
component: () => <Outlet />,
// ... root route options
})
const routeTree = rootRoute.addChildren([
// ... other routes
])
const router = createRouter({
routeTree,
})
\`\`\`
# RouteApi class
> [!CAUTION]
> This class has been deprecated and will be removed in the next major version of TanStack Router.
> Please use the [\`getRouteApi\`](../getRouteApiFunction.md) function instead.
The \`RouteApi\` class provides type-safe version of common hooks like \`useParams\`, \`useSearch\`, \`useRouteContext\`, \`useNavigate\`, \`useLoaderData\`, and \`useLoaderDeps\` that are pre-bound to a specific route ID and corresponding registered route types.
## Constructor options
The \`RouteApi\` constructor accepts a single argument: the \`options\` that will be used to configure the \`RouteApi\` instance.
### \`opts.routeId\` option
- Type: \`string\`
- Required
- The route ID to which the \`RouteApi\` instance will be bound
## Constructor returns
- An instance of the [\`RouteApi\`](../RouteApiType.md) that is pre-bound to the route ID that it was called with.
## Examples
\`\`\`tsx
import { RouteApi } from '@tanstack/react-router'
const routeApi = new RouteApi({ id: '/posts' })
export function PostsPage() {
const posts = routeApi.useLoaderData()
// ...
}
\`\`\`
# RouteApi Type
The \`RouteApi\` describes an instance that provides type-safe versions of common hooks like \`useParams\`, \`useSearch\`, \`useRouteContext\`, \`useNavigate\`, \`useLoaderData\`, and \`useLoaderDeps\` that are pre-bound to a specific route ID and corresponding registered route types.
## \`RouteApi\` properties and methods
The \`RouteApi\` has the following properties and methods:
### \`useMatch\` method
\`\`\`tsx
useMatch<TSelected = TAllContext>(opts?: {
select?: (match: TAllContext) => TSelected
}): TSelected
\`\`\`
- A type-safe version of the [\`useMatch\`](../useMatchHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
- Options
- \`opts.select\`
- Optional
- \`(match: RouteMatch) => TSelected\`
- If supplied, this function will be called with the route match and the return value will be returned from \`useMatch\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
- \`opts.structuralSharing\`
- Optional
- \`boolean\`
- Configures whether structural sharing is enabled for the value returned by \`select\`.
- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
- Returns
- If a \`select\` function is provided, the return value of the \`select\` function.
- If no \`select\` function is provided, the \`RouteMatch\` object or a loosened version of the \`RouteMatch\` object if \`opts.strict\` is \`false\`.
### \`useRouteContext\` method
\`\`\`tsx
useRouteContext<TSelected = TAllContext>(opts?: {
select?: (search: TAllContext) => TSelected
}): TSelected
\`\`\`
- A type-safe version of the [\`useRouteContext\`](../useRouteContextHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
- Options
- \`opts.select\`
- Optional
- \`(match: RouteContext) => TSelected\`
- If supplied, this function will be called with the route match and the return value will be returned from \`useRouteContext\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
- Returns
- If a \`select\` function is provided, the return value of the \`select\` function.
- If no \`select\` function is provided, the \`RouteContext\` object or a loosened version of the \`RouteContext\` object if \`opts.strict\` is \`false\`.
### \`useSearch\` method
\`\`\`tsx
useSearch<TSelected = TFullSearchSchema>(opts?: {
select?: (search: TFullSearchSchema) => TSelected
}): TSelected
\`\`\`
- A type-safe version of the [\`useSearch\`](../useSearchHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
- Options
- \`opts.select\`
- Optional
- \`(match: TFullSearchSchema) => TSelected\`
- If supplied, this function will be called with the route match and the return value will be returned from \`useSearch\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
- \`opts.structuralSharing\`
- Optional
- \`boolean\`
- Configures whether structural sharing is enabled for the value returned by \`select\`.
- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
- Returns
- If a \`select\` function is provided, the return value of the \`select\` function.
- If no \`select\` function is provided, the \`TFullSearchSchema\` object or a loosened version of the \`TFullSearchSchema\` object if \`opts.strict\` is \`false\`.
### \`useParams\` method
\`\`\`tsx
useParams<TSelected = TAllParams>(opts?: {
select?: (params: TAllParams) => TSelected
}): TSelected
\`\`\`
- A type-safe version of the [\`useParams\`](../useParamsHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
- Options
- \`opts.select\`
- Optional
- \`(match: TAllParams) => TSelected\`
- If supplied, this function will be called with the route match and the return value will be returned from \`useParams\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
- \`opts.structuralSharing\`
- Optional
- \`boolean\`
- Configures whether structural sharing is enabled for the value returned by \`select\`.
- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
- Returns
- If a \`select\` function is provided, the return value of the \`select\` function.
- If no \`select\` function is provided, the \`TAllParams\` object or a loosened version of the \`TAllParams\` object if \`opts.strict\` is \`false\`.
### \`useLoaderData\` method
\`\`\`tsx
useLoaderData<TSelected = TLoaderData>(opts?: {
select?: (search: TLoaderData) => TSelected
}): TSelected
\`\`\`
- A type-safe version of the [\`useLoaderData\`](../useLoaderDataHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
- Options
- \`opts.select\`
- Optional
- \`(match: TLoaderData) => TSelected\`
- If supplied, this function will be called with the route match and the return value will be returned from \`useLoaderData\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
- \`opts.structuralSharing\`
- Optional
- \`boolean\`
- Configures whether structural sharing is enabled for the value returned by \`select\`.
- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
- Returns
- If a \`select\` function is provided, the return value of the \`select\` function.
- If no \`select\` function is provided, the \`TLoaderData\` object or a loosened version of the \`TLoaderData\` object if \`opts.strict\` is \`false\`.
### \`useLoaderDeps\` method
\`\`\`tsx
useLoaderDeps<TSelected = TLoaderDeps>(opts?: {
select?: (search: TLoaderDeps) => TSelected
}): TSelected
\`\`\`
- A type-safe version of the [\`useLoaderDeps\`](../useLoaderDepsHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
- Options
- \`opts.select\`
- Optional
- \`(match: TLoaderDeps) => TSelected\`
- If supplied, this function will be called with the route match and the return value will be returned from \`useLoaderDeps\`.
- \`opts.structuralSharing\`
- Optional
- \`boolean\`
- Configures whether structural sharing is enabled for the value returned by \`select\`.
- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
- Returns
- If a \`select\` function is provided, the return value of the \`select\` function.
- If no \`select\` function is provided, the \`TLoaderDeps\` object.
### \`useNavigate\` method
\`\`\`tsx
useNavigate(): // navigate function
\`\`\`
- A type-safe version of [\`useNavigate\`](../useNavigateHook.md) that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
# Route class
> [!CAUTION]
> This class has been deprecated and will be removed in the next major version of TanStack Router.
> Please use the [\`createRoute\`](../createRouteFunction.md) function instead.
The \`Route\` class implements the \`RouteApi\` class and can be used to create route instances. A route instance can then be used to create a route tree.
## \`Route\` constructor
The \`Route\` constructor accepts an object as its only argument.
### Constructor options
- Type: [\`RouteOptions\`](../RouteOptionsType.md)
- Required
- The options that will be used to configure the route instance
### Constructor returns
A new [\`Route\`](../RouteType.md) instance.
## Examples
\`\`\`tsx
import { Route } from '@tanstack/react-router'
import { rootRoute } from './__root'
const indexRoute = new Route({
getParentRoute: () => rootRoute,
path: '/',
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = indexRoute.useLoaderData()
return <div>{data}</div>
}
\`\`\`
# RouteMask type
The \`RouteMask\` type extends the [\`ToOptions\`](../ToOptionsType.md) type and has other the necessary properties to create a route mask.
## RouteMask properties
The \`RouteMask\` type accepts an object with the following properties:
### \`...ToOptions\`
- Type: [\`ToOptions\`](../ToOptionsType.md)
- Required
- The options that will be used to configure the route mask
### \`options.routeTree\`
- Type: \`TRouteTree\`
- Required
- The route tree that this route mask will support
### \`options.unmaskOnReload\`
- Type: \`boolean\`
- Optional
- If \`true\`, the route mask will be removed when the page is reloaded
# RouteMatch type
The \`RouteMatch\` type represents a route match in TanStack Router.
\`\`\`tsx
interface RouteMatch {
id: string
routeId: string
pathname: string
params: Route['allParams']
status: 'pending' | 'success' | 'error'
isFetching: boolean
showPending: boolean
error: unknown
paramsError: unknown
searchError: unknown
updatedAt: number
loadPromise?: Promise<void>
loaderData?: Route['loaderData']
context: Route['allContext']
search: Route['fullSearchSchema']
fetchedAt: number
abortController: AbortController
cause: 'enter' | 'stay'
}
\`\`\`
# RouteOptions type
The \`RouteOptions\` type is used to describe the options that can be used when creating a route.
## RouteOptions properties
The \`RouteOptions\` type accepts an object with the following properties:
### \`getParentRoute\` method
- Type: \`() => TParentRoute\`
- Required
- A function that returns the parent route of the route being created. This is required to provide full type safety to child route configurations and to ensure that the route tree is built correctly.
### \`path\` property
- Type: \`string\`
- Required, unless an \`id\` is provided to configure the route as a pathless layout route
- The path segment that will be used to match the route.
### \`id\` property
- Type: \`string\`
- Optional, but required if a \`path\` is not provided
- The unique identifier for the route if it is to be configured as a pathless layout route. If provided, the route will not match against the location pathname and its routes will be flattened into its parent route for matching.
### \`component\` property
- Type: \`RouteComponent\` or \`LazyRouteComponent\`
- Optional - Defaults to \`<Outlet />\`
- The content to be rendered when the route is matched.
### \`errorComponent\` property
- Type: \`RouteComponent\` or \`LazyRouteComponent\`
- Optional - Defaults to \`routerOptions.defaultErrorComponent\`
- The content to be rendered when the route encounters an error.
### \`pendingComponent\` property
- Type: \`RouteComponent\` or \`LazyRouteComponent\`
- Optional - Defaults to \`routerOptions.defaultPendingComponent\`
- The content to be rendered if and when the route is pending and has reached its pendingMs threshold.
### \`notFoundComponent\` property
- Type: \`NotFoundRouteComponent\` or \`LazyRouteComponent\`
- Optional - Defaults to \`routerOptions.defaultNotFoundComponent\`
- The content to be rendered when the route is not found.
### \`validateSearch\` method
- Type: \`(rawSearchParams: unknown) => TSearchSchema\`
- Optional
- A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router.
- Optionally, the parameter type can be tagged with the \`SearchSchemaInput\` type like this: \`(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema\`. If this tag is present, \`TSearchSchemaInput\` will be used to type the \`search\` property of \`<Link />\` and \`navigate()\` **instead of** \`TSearchSchema\`. The difference between \`TSearchSchemaInput\` and \`TSearchSchema\` can be useful, for example, to express optional search parameters.
### \`search.middlewares\` property
- Type: \`(({search: TSearchSchema, next: (newSearch: TSearchSchema) => TSearchSchema}) => TSearchSchema)[]\`
- Optional
- Search middlewares are functions that transform the search parameters when generating new links for a route or its descendants.
- A search middleware is passed in the current search (if it is the first middleware to run) or is invoked by the previous middleware calling \`next\`.
### \`parseParams\` method (⚠️ deprecated, use \`params.parse\` instead)
- Type: \`(rawParams: Record<string, string>) => TParams\`
- Optional
- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router.
### \`stringifyParams\` method (⚠️ deprecated, use \`params.stringify\` instead)
- Type: \`(params: TParams) => Record<string, string>\`
- Required if \`parseParams\` is provided
- A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of \`Record<string, string>\` mapping.
### \`params.parse\` method
- Type: \`(rawParams: Record<string, string>) => TParams\`
- Optional
- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router.
### \`params.stringify\` method
- Type: \`(params: TParams) => Record<string, string>\`
- A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of \`Record<string, string>\` mapping.
### \`beforeLoad\` method
- Type:
\`\`\`tsx
type beforeLoad = (
opts: RouteMatch & {
search: TFullSearchSchema
abortController: AbortController
preload: boolean
params: TAllParams
context: TParentContext
location: ParsedLocation
navigate: NavigateFn<AnyRoute> // @deprecated
buildLocation: BuildLocationFn<AnyRoute>
cause: 'enter' | 'stay'
},
) => Promise<TRouteContext> | TRouteContext | void
\`\`\`
- Optional
- [\`ParsedLocation\`](../ParsedLocationType.md)
- This async function is called before a route is loaded. If an error is thrown here, the route's loader will not be called and the route will not render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the \`onError\` function. If thrown during a preload event, the error will be logged to the console and the preload will fail.
- If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the \`pendingComponent\` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render.
- If this function returns a \`TRouteContext\` object, that object will be merged into the route's context and be made available in the \`loader\` and other related route components/methods.
- It's common to use this function to check if a user is authenticated and redirect them to a login page if they are not. To do this, you can either return or throw a \`redirect\` object from this function.
> 🚧 \`opts.navigate\` has been deprecated and will be removed in the next major release. Use \`throw redirect({ to: '/somewhere' })\` instead. Read more about the \`redirect\` function [here](../redirectFunction.md).
### \`loader\` method
- Type:
\`\`\`tsx
type loader = (
opts: RouteMatch & {
abortController: AbortController
cause: 'preload' | 'enter' | 'stay'
context: TAllContext
deps: TLoaderDeps
location: ParsedLocation
params: TAllParams
preload: boolean
parentMatchPromise: Promise<MakeRouteMatchFromRoute<TParentRoute>>
navigate: NavigateFn<AnyRoute> // @deprecated
route: AnyRoute
},
) => Promise<TLoaderData> | TLoaderData | void
\`\`\`
- Optional
- [\`ParsedLocation\`](../ParsedLocationType.md)
- This async function is called when a route is matched and passed the route's match object. If an error is thrown here, the route will be put into an error state and the error will be thrown during render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the \`onError\` function. If thrown during a preload event, the error will be logged to the console and the preload will fail.
- If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the \`pendingComponent\` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render.
- If this function returns a \`TLoaderData\` object, that object will be stored on the route match until the route match is no longer active. It can be accessed using the \`useLoaderData\` hook in any component that is a child of the route match before another \`<Outlet />\` is rendered.
- Deps must be returned by your \`loaderDeps\` function in order to appear.
> 🚧 \`opts.navigate\` has been deprecated and will be removed in the next major release. Use \`throw redirect({ to: '/somewhere' })\` instead. Read more about the \`redirect\` function [here](../redirectFunction.md).
### \`loaderDeps\` method
- Type:
\`\`\`tsx
type loaderDeps = (opts: { search: TFullSearchSchema }) => Record<string, any>
\`\`\`
- Optional
- A function that will be called before this route is matched to provide additional unique identification to the route match and serve as a dependency tracker for when the match should be reloaded. It should return any serializable value that can uniquely identify the route match from navigation to navigation.
- By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here.
- If your route match relies on search params for unique identification, it's required that you return them here so they can be made available in the \`loader\`'s \`deps\` argument.
### \`staleTime\` property
- Type: \`number\`
- Optional
- Defaults to \`routerOptions.defaultStaleTime\`, which defaults to \`0\`
- The amount of time in milliseconds that a route match's loader data will be considered fresh. If a route match is matched again within this time frame, its loader data will not be reloaded.
### \`preloadStaleTime\` property
- Type: \`number\`
- Optional
- Defaults to \`routerOptions.defaultPreloadStaleTime\`, which defaults to \`30_000\` ms (30 seconds)
- The amount of time in milliseconds that a route match's loader data will be considered fresh when preloading. If a route match is preloaded again within this time frame, its loader data will not be reloaded. If a route match is loaded (for navigation) within this time frame, the normal \`staleTime\` is used instead.
### \`gcTime\` property
- Type: \`number\`
- Optional
- Defaults to \`routerOptions.defaultGcTime\`, which defaults to 30 minutes.
- The amount of time in milliseconds that a route match's loader data will be kept in memory after a preload or it is no longer in use.
### \`shouldReload\` property
- Type: \`boolean | ((args: LoaderArgs) => boolean)\`
- Optional
- If \`false\` or returns \`false\`, the route match's loader data will not be reloaded on subsequent matches.
- If \`true\` or returns \`true\`, the route match's loader data will be reloaded on subsequent matches.
- If \`undefined\` or returns \`undefined\`, the route match's loader data will adhere to the default stale-while-revalidate behavior.
### \`caseSensitive\` property
- Type: \`boolean\`
- Optional
- If \`true\`, this route will be matched as case-sensitive.
### \`wrapInSuspense\` property
- Type: \`boolean\`
- Optional
- If \`true\`, this route will be forcefully wrapped in a suspense boundary, regardless if a reason is found to do so from inspecting its provided components.
### \`pendingMs\` property
- Type: \`number\`
- Optional
- Defaults to \`routerOptions.defaultPendingMs\`, which defaults to \`1000\`
- The threshold in milliseconds that a route must be pending before its \`pendingComponent\` is shown.
### \`pendingMinMs\` property
- Type: \`number\`
- Optional
- Defaults to \`routerOptions.defaultPendingMinMs\` which defaults to \`500\`
- The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second.
### \`preloadMaxAge\` property
- Type: \`number\`
- Optional
- Defaults to \`30_000\` ms (30 seconds)
- The maximum amount of time in milliseconds that a route's preloaded route data will be cached for. If a route is not matched within this time frame, its loader data will be discarded.
### \`preSearchFilters\` property (⚠️ deprecated, use \`search.middlewares\` instead)
- Type: \`((search: TFullSearchSchema) => TFullSearchSchema)[]\`
- Optional
- An array of functions that will be called when generating any new links to this route or its grandchildren.
- Each function will be called with the current search params and should return a new search params object that will be used to generate the link.
- It has a \`pre\` prefix because it is called before the user-provided function that is passed to \`navigate\`/\`Link\` etc has a chance to modify the search params.
### \`postSearchFilters\` property (⚠️ deprecated, use \`search.middlewares\` instead)
- Type: \`((search: TFullSearchSchema) => TFullSearchSchema)[]\`
- Optional
- An array of functions that will be called when generating any new links to this route or its grandchildren.
- Each function will be called with the current search params and should return a new search params object that will be used to generate the link.
- It has a \`post\` prefix because it is called after the user-provided function that is passed to \`navigate\`/\`Link\` etc has modified the search params.
### \`onError\` property
- Type: \`(error: any) => void\`
- Optional
- A function that will be called when an error is thrown during a navigation or preload event.
- If this function throws a [\`redirect\`](../redirectFunction.md), then the router will process and apply the redirect immediately.
### \`onEnter\` property
- Type: \`(match: RouteMatch) => void\`
- Optional
- A function that will be called when a route is matched and loaded after not being matched in the previous location.
### \`onStay\` property
- Type: \`(match: RouteMatch) => void\`
- Optional
- A function that will be called when a route is matched and loaded after being matched in the previous location.
### \`onLeave\` property
- Type: \`(match: RouteMatch) => void\`
- Optional
- A function that will be called when a route is no longer matched after being matched in the previous location.
### \`onCatch\` property
- Type: \`(error: Error, errorInfo: ErrorInfo) => void\`
- Optional - Defaults to \`routerOptions.defaultOnCatch\`
- A function that will be called when errors are caught when the route encounters an error.
### \`remountDeps\` method
- Type:
\`\`\`tsx
type remountDeps = (opts: RemountDepsOptions) => any
interface RemountDepsOptions<
in out TRouteId,
in out TFullSearchSchema,
in out TAllParams,
in out TLoaderDeps,
> {
routeId: TRouteId
search: TFullSearchSchema
params: TAllParams
loaderDeps: TLoaderDeps
}
\`\`\`
- Optional
- A function that will be called to determine whether a route component shall be remounted after navigation. If this function returns a different value than previously, it will remount.
- The return value needs to be JSON serializable.
- By default, a route component will not be remounted if it stays active after a navigation.
Example:
If you want to configure to remount a route component upon \`params\` change, use:
\`\`\`tsx
remountDeps: ({ params }) => params
\`\`\`
# Route type
The \`Route\` type is used to describe a route instance.
## \`Route\` properties and methods
An instance of the \`Route\` has the following properties and methods:
### \`.addChildren\` method
- Type: \`(children: Route[]) => this\`
- Adds child routes to the route instance and returns the route instance (but with updated types to reflect the new children).
### \`.update\` method
- Type: \`(options: Partial<UpdatableRouteOptions>) => this\`
- Updates the route instance with new options and returns the route instance (but with updated types to reflect the new options).
- In some circumstances, it can be useful to update a route instance's options after it has been created to avoid circular type references.
- ...\`RouteApi\` methods
### \`.lazy\` method
- Type: \`(lazyImporter: () => Promise<Partial<UpdatableRouteOptions>>) => this\`
- Updates the route instance with a new lazy importer which will be resolved lazily when loading the route. This can be useful for code splitting.
### ...\`RouteApi\` methods
- All of the methods from [\`RouteApi\`](../RouteApiType.md) are available.
# Router Class
> [!CAUTION]
> This class has been deprecated and will be removed in the next major version of TanStack Router.
> Please use the [\`createRouter\`](../createRouterFunction.md) function instead.
The \`Router\` class is used to instantiate a new router instance.
## \`Router\` constructor
The \`Router\` constructor accepts a single argument: the \`options\` that will be used to configure the router instance.
### Constructor options
- Type: [\`RouterOptions\`](../RouterOptionsType.md)
- Required
- The options that will be used to configure the router instance.
### Constructor returns
- An instance of the [\`Router\`](../RouterType.md).
## Examples
\`\`\`tsx
import { Router, RouterProvider } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = new Router({
routeTree,
defaultPreload: 'intent',
})
export default function App() {
return <RouterProvider router={router} />
}
\`\`\`
# RouterEvents type
The \`RouterEvents\` type contains all of the events that the router can emit. Each top-level key of this type, represents the name of an event that the router can emit. The values of the keys are the event payloads.
\`\`\`tsx
type RouterEvents = {
onBeforeNavigate: {
type: 'onBeforeNavigate'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
}
onBeforeLoad: {
type: 'onBeforeLoad'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
}
onLoad: {
type: 'onLoad'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
}
onResolved: {
type: 'onResolved'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
}
onBeforeRouteMount: {
type: 'onBeforeRouteMount'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
}
onInjectedHtml: {
type: 'onInjectedHtml'
promise: Promise<string>
}
onRendered: {
type: 'onRendered'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
}
}
\`\`\`
## RouterEvents properties
Once an event is emitted, the following properties will be present on the event payload.
### \`type\` property
- Type: \`onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved\`
- The type of the event
- This is useful for discriminating between events in a listener function.
### \`fromLocation\` property
- Type: [\`ParsedLocation\`](../ParsedLocationType.md)
- The location that the router is transitioning from.
### \`toLocation\` property
- Type: [\`ParsedLocation\`](../ParsedLocationType.md)
- The location that the router is transitioning to.
### \`pathChanged\` property
- Type: \`boolean\`
- \`true\` if the path has changed between the \`fromLocation\` and \`toLocation\`.
### \`hrefChanged\` property
- Type: \`boolean\`
- \`true\` if the href has changed between the \`fromLocation\` and \`toLocation\`.
## Example
\`\`\`tsx
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({ routeTree })
const unsub = router.subscribe('onResolved', (evt) => {
// ...
})
\`\`\`
# RouterOptions
The \`RouterOptions\` type contains all of the options that can be used to configure a router instance.
## RouterOptions properties
The \`RouterOptions\` type accepts an object with the following properties and methods:
### \`routeTree\` property
- Type: \`AnyRoute\`
- Required
- The route tree that will be used to configure the router instance.
### \`history\` property
- Type: \`RouterHistory\`
- Optional
- The history object that will be used to manage the browser history. If not provided, a new \`createBrowserHistory\` instance will be created and used.
### \`stringifySearch\` method
- Type: \`(search: Record<string, any>) => string\`
- Optional
- A function that will be used to stringify search params when generating links.
- Defaults to \`defaultStringifySearch\`.
### \`parseSearch\` method
- Type: \`(search: string) => Record<string, any>\`
- Optional
- A function that will be used to parse search params when parsing the current location.
- Defaults to \`defaultParseSearch\`.
### \`search.strict\` property
- Type: \`boolean\`
- Optional
- Defaults to \`false\`
- Configures how unknown search params (= not returned by any \`validateSearch\`) are treated.
- If \`false\`, unknown search params will be kept.
- If \`true\`, unknown search params will be removed.
### \`defaultPreload\` property
- Type: \`undefined | false | 'intent' | 'viewport' | 'render'\`
- Optional
- Defaults to \`false\`
- If \`false\`, routes will not be preloaded by default in any way.
- If \`'intent'\`, routes will be preloaded by default when the user hovers over a link or a \`touchstart\` event is detected on a \`<Link>\`.
- If \`'viewport'\`, routes will be preloaded by default when they are within the viewport of the browser.
- If \`'render'\`, routes will be preloaded by default as soon as they are rendered in the DOM.
### \`defaultPreloadDelay\` property
- Type: \`number\`
- Optional
- Defaults to \`50\`
- The delay in milliseconds that a route must be hovered over or touched before it is preloaded.
### \`defaultComponent\` property
- Type: \`RouteComponent\`
- Optional
- Defaults to \`Outlet\`
- The default \`component\` a route should use if no component is provided.
### \`defaultErrorComponent\` property
- Type: \`RouteComponent\`
- Optional
- Defaults to \`ErrorComponent\`
- The default \`errorComponent\` a route should use if no error component is provided.
### \`defaultNotFoundComponent\` property
- Type: \`NotFoundRouteComponent\`
- Optional
- Defaults to \`NotFound\`
- The default \`notFoundComponent\` a route should use if no notFound component is provided.
### \`defaultPendingComponent\` property
- Type: \`RouteComponent\`
- Optional
- The default \`pendingComponent\` a route should use if no pending component is provided.
### \`defaultPendingMs\` property
- Type: \`number\`
- Optional
- Defaults to \`1000\`
- The default \`pendingMs\` a route should use if no pendingMs is provided.
### \`defaultPendingMinMs\` property
- Type: \`number\`
- Optional
- Defau