- Spec files
npm-tanstack--react-router
Describes: pkg:npm/@tanstack/react-router@1.132.x
- Description
- Modern and scalable routing for React applications with built-in data fetching, caching, and state management capabilities
- Author
- tessl
- Last updated
How to use
npx @tessl/cli registry install tessl/npm-tanstack--react-router@1.132.0
navigation-links.md docs/
1# Navigation & Links23Navigation utilities, link components, and programmatic navigation with type-safe parameter handling, URL masking, and advanced navigation features.45## Capabilities67### Redirection89Create redirect responses for use in route loaders and actions.1011```typescript { .api }12/**13* Create a redirect response14* @param options - Redirect configuration options15* @returns Redirect object for throwing from loaders/actions16*/17function redirect<TRouter extends AnyRouter = AnyRouter>(18options: RedirectOptions<TRouter>19): Redirect;2021interface RedirectOptions<TRouter extends AnyRouter = AnyRouter> {22/** Redirect destination path */23to?: string;24/** Search parameters for redirect */25search?: Record<string, any> | ((current: any) => Record<string, any>);26/** Path parameters for redirect */27params?: Record<string, any>;28/** Hash fragment for redirect */29hash?: string | ((current: string) => string);30/** History state */31state?: any;32/** Use replace instead of push */33replace?: boolean;34/** HTTP status code (SSR) */35statusCode?: number;36/** HTTP headers (SSR) */37headers?: Record<string, string>;38}3940/**41* Type guard for redirect objects42* @param obj - Object to check43* @returns Whether object is a redirect44*/45function isRedirect(obj: any): obj is Redirect;4647interface Redirect {48code: "REDIRECT";49statusCode: number;50headers: Record<string, string>;51href: string;52}53```5455**Usage Examples:**5657```typescript58import { redirect } from "@tanstack/react-router";5960// In route loader61const postRoute = createRoute({62path: "/posts/$postId",63loader: async ({ params, context }) => {64const post = await fetchPost(params.postId);6566// Redirect if post not found67if (!post) {68throw redirect({69to: "/404",70statusCode: 404,71});72}7374// Redirect if user doesn't have permission75if (!context.user.canViewPost(post)) {76throw redirect({77to: "/login",78search: { redirect: `/posts/${params.postId}` },79replace: true,80});81}8283return { post };84},85});8687// Conditional redirect in component88function ProtectedRoute() {89const { user } = useRouteContext();9091if (!user) {92throw redirect({ to: "/login" });93}9495return <Dashboard />;96}97```9899### Link Utilities100101Utilities for creating custom link components and validating link options.102103```typescript { .api }104/**105* Create a custom link component with any element106* @param Comp - Base component to wrap with link functionality107* @returns Link component with router functionality108*/109function createLink<TComp extends React.ComponentType<any>>(110Comp: TComp111): LinkComponent<TComp>;112113/**114* Validate and return link options with type safety115* @param options - Link options to validate116* @returns Validated link options117*/118function linkOptions<119TRouter extends AnyRouter = RegisteredRouter,120TFrom extends string = string,121TTo extends string | undefined = undefined,122TMaskFrom extends string = TFrom,123TMaskTo extends string = ""124>(125options: LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>126): LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>;127128type LinkComponent<TComp> = React.ForwardRefExoticComponent<129Omit<React.ComponentProps<TComp>, keyof LinkProps> & LinkProps130>;131```132133**Usage Examples:**134135```typescript136import { createLink, linkOptions } from "@tanstack/react-router";137138// Create custom link with button139const ButtonLink = createLink("button");140141function CustomNavigation() {142return (143<ButtonLink144to="/dashboard"145params={{ userId: "123" }}146activeProps={{ className: "active-button" }}147>148Dashboard149</ButtonLink>150);151}152153// Create link with custom component154const CardLink = createLink(({ children, ...props }) => (155<div className="card" {...props}>156{children}157</div>158));159160// Validate link options161function ValidatedLink({ to, ...options }) {162const validatedOptions = linkOptions({163to,164preload: "intent",165activeOptions: { exact: true },166...options,167});168169return <Link {...validatedOptions} />;170}171```172173### Navigation History174175Create and manage browser history for navigation.176177```typescript { .api }178/**179* Create a browser history instance180* @param options - Browser history options181* @returns Browser history instance182*/183function createBrowserHistory(options?: {184basename?: string;185window?: Window;186}): RouterHistory;187188/**189* Create a hash history instance190* @param options - Hash history options191* @returns Hash history instance192*/193function createHashHistory(options?: {194basename?: string;195window?: Window;196}): RouterHistory;197198/**199* Create a memory history instance for testing/SSR200* @param options - Memory history options201* @returns Memory history instance202*/203function createMemoryHistory(options?: {204initialEntries?: string[];205initialIndex?: number;206}): RouterHistory;207208/**209* Create a history instance (base function)210* @param options - History options211* @returns History instance212*/213function createHistory(options: {214getLocation: () => HistoryLocation;215listener: (fn: () => void) => () => void;216pushState: (path: string, state?: any) => void;217replaceState: (path: string, state?: any) => void;218go: (n: number) => void;219back: () => void;220forward: () => void;221createHref?: (path: string) => string;222}): RouterHistory;223```224225**Usage Examples:**226227```typescript228import { createBrowserHistory, createMemoryHistory, createRouter } from "@tanstack/react-router";229230// Browser history with basename231const history = createBrowserHistory({232basename: "/app",233});234235const router = createRouter({236routeTree,237history,238});239240// Memory history for testing241const testHistory = createMemoryHistory({242initialEntries: ["/", "/about", "/contact"],243initialIndex: 1, // Start at /about244});245246// Hash history247const hashHistory = createHashHistory();248```249250### Navigation Blocking251252Utilities for blocking navigation under certain conditions.253254```typescript { .api }255type BlockerFn = (args: {256fromLocation: ParsedLocation;257toLocation: ParsedLocation;258}) => boolean | Promise<boolean>;259260type ShouldBlockFn = (261fromLocation: ParsedLocation,262toLocation: ParsedLocation263) => boolean;264```265266### Route Matching Utilities267268Utilities for checking route matches and building navigation options.269270```typescript { .api }271/**272* Check if current location matches route pattern273* @param basepath - Base path274* @param currentPathname - Current pathname275* @param matchLocation - Location to match against276* @returns Match result or false277*/278function matchPathname(279basepath: string,280currentPathname: string,281matchLocation: MatchLocation282): MatchPathResult | false;283284/**285* Match route by path pattern286* @param basepath - Base path287* @param currentPathname - Current pathname288* @param matchLocation - Location to match against289* @returns Match result or false290*/291function matchByPath(292basepath: string,293currentPathname: string,294matchLocation: MatchLocation295): MatchPathResult | false;296297interface MatchLocation {298to: string;299params?: Record<string, any>;300search?: Record<string, any>;301hash?: string;302fuzzy?: boolean;303includeSearch?: boolean;304includeHash?: boolean;305}306307interface MatchPathResult {308params: Record<string, string>;309}310```311312### Build Navigation Functions313314Utilities for building navigation and location objects.315316```typescript { .api }317type BuildLocationFn<TRouter extends AnyRouter = AnyRouter> = <318TFrom extends RoutePaths<TRouter> = "/",319TTo extends string = "."320>(321opts: BuildLocationOptions<TRouter, TFrom, TTo>322) => ParsedLocation;323324interface BuildLocationOptions<TRouter extends AnyRouter, TFrom extends RoutePaths<TRouter>, TTo extends string> {325to?: TTo;326from?: TFrom;327params?: Record<string, any>;328search?: Record<string, any> | ((prev: any) => Record<string, any>);329hash?: string | ((prev: string) => string);330state?: any;331}332333type NavigateFn<TRouter extends AnyRouter = AnyRouter> = <334TFrom extends RoutePaths<TRouter> = "/",335TTo extends string = "."336>(337opts: NavigateOptions<TRouter, TFrom, TTo>338) => Promise<void>;339```340341### Navigation Options Validation342343Type-safe validation utilities for navigation options.344345```typescript { .api }346type ValidateNavigateOptions<TRouter extends AnyRouter, TFrom extends string, TTo extends string> =347NavigateOptions<TRouter, TFrom, TTo>;348349type ValidateNavigateOptionsArray<T> = T extends ReadonlyArray<infer U>350? U extends { to: infer TTo; from?: infer TFrom }351? TTo extends string352? TFrom extends string | undefined353? ValidateNavigateOptions<RegisteredRouter, TFrom extends string ? TFrom : "/", TTo>354: never355: never356: never357: never;358359type ValidateRedirectOptions<TRouter extends AnyRouter, TFrom extends string, TTo extends string> =360RedirectOptions<TRouter>;361362type ValidateRedirectOptionsArray<T> = T extends ReadonlyArray<infer U>363? U extends { to: infer TTo; from?: infer TFrom }364? TTo extends string365? TFrom extends string | undefined366? ValidateRedirectOptions<RegisteredRouter, TFrom extends string ? TFrom : "/", TTo>367: never368: never369: never370: never;371```372373## Types374375### Core Navigation Types376377```typescript { .api }378interface NavigateOptions<379TRouter extends AnyRouter = AnyRouter,380TFrom extends RoutePaths<TRouter> = "/",381TTo extends string = "."382> {383/** Destination path */384to?: TTo;385/** Source path for relative navigation */386from?: TFrom;387/** Path parameters */388params?: MakeRouteMatch<TRouter, TFrom, TTo>["params"];389/** Search parameters */390search?: MakeRouteMatch<TRouter, TFrom, TTo>["search"] | ((prev: any) => any);391/** Hash fragment */392hash?: string | ((prev: string) => string);393/** History state */394state?: any;395/** Route mask options */396mask?: ToMaskOptions<TRouter, TFrom, TTo>;397/** Use replace instead of push */398replace?: boolean;399/** Reset scroll position */400resetScroll?: boolean;401/** Scroll hash target into view */402hashScrollIntoView?: boolean;403/** Wrap navigation in startTransition */404startTransition?: boolean;405/** Enable view transitions */406viewTransition?: boolean;407/** Ignore navigation blockers */408ignoreBlocker?: boolean;409}410411interface LinkOptions<412TRouter extends AnyRouter = AnyRouter,413TFrom extends string = string,414TTo extends string | undefined = undefined,415TMaskFrom extends string = TFrom,416TMaskTo extends string = ""417> extends NavigateOptions<TRouter, TFrom, TTo> {418/** Props when link is active */419activeProps?:420| React.AnchorHTMLAttributes<HTMLAnchorElement>421| (() => React.AnchorHTMLAttributes<HTMLAnchorElement>);422/** Props when link is inactive */423inactiveProps?:424| React.AnchorHTMLAttributes<HTMLAnchorElement>425| (() => React.AnchorHTMLAttributes<HTMLAnchorElement>);426/** Active link matching options */427activeOptions?: ActiveLinkOptions;428/** Preload strategy */429preload?: false | "intent" | "render" | "viewport";430/** Preload delay in milliseconds */431preloadDelay?: number;432/** Disabled state */433disabled?: boolean;434}435436interface ActiveLinkOptions {437/** Exact path matching */438exact?: boolean;439/** Include search parameters in matching */440includeSearch?: boolean;441/** Include hash in matching */442includeHash?: boolean;443}444```445446### Route Masking Types447448```typescript { .api }449interface ToMaskOptions<450TRouter extends AnyRouter = AnyRouter,451TFrom extends string = string,452TTo extends string = string453> {454/** Masked destination */455to?: string;456/** Masked parameters */457params?: Record<string, any>;458/** Masked search parameters */459search?: Record<string, any> | ((prev: any) => any);460/** Masked hash */461hash?: string | ((prev: string) => string);462/** Unmask on reload */463unmaskOnReload?: boolean;464}465466interface RouteMask {467from: string;468to: string;469params?: Record<string, any>;470search?: Record<string, any>;471hash?: string;472unmaskOnReload?: boolean;473}474```475476### Path Resolution Types477478```typescript { .api }479type ToPathOption<480TRouter extends AnyRouter = AnyRouter,481TFrom extends RoutePaths<TRouter> = "/",482TTo extends string = string483> = TTo | RelativeToPathAutoComplete<TRouter, TFrom, TTo>;484485type RelativeToPathAutoComplete<486TRouter extends AnyRouter,487TFrom extends string,488TTo extends string489> = TTo extends `..${infer _}`490? "../"491: TTo extends `./${infer _}`492? "./"493: TTo;494495type AbsoluteToPath<TRouter extends AnyRouter, TTo extends string> = TTo;496497type RelativeToPath<498TRouter extends AnyRouter,499TFrom extends string,500TTo extends string501> = TTo extends "."502? TFrom503: TTo extends `..${infer Rest}`504? RelativeToParentPath<TRouter, TFrom, Rest>505: TTo extends `./${infer Rest}`506? RelativeToCurrentPath<TRouter, TFrom, Rest>507: never;508```