- 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
router-creation.md docs/
1# Router Creation & Configuration23Core router setup and configuration for creating type-safe routing instances with comprehensive options for data loading, caching, error handling, and SSR support.45## Capabilities67### Router Creation89Creates a new router instance with the specified route tree and configuration options.1011```typescript { .api }12/**13* Create a router instance with route tree and configuration14* @param options - Router configuration options including route tree, history, and defaults15* @returns Router instance for use with RouterProvider16*/17function createRouter<TRouteTree extends AnyRoute>(18options: RouterConstructorOptions<TRouteTree>19): Router<TRouteTree>;2021interface RouterConstructorOptions<TRouteTree extends AnyRoute> {22/** The route tree defining all application routes */23routeTree: TRouteTree;24/** History instance for navigation (defaults to createBrowserHistory()) */25history?: RouterHistory;26/** Base path for the router */27basepath?: string;28/** Router context shared across all routes */29context?: TRouterContext;30/** Default preload strategy for routes */31defaultPreload?: false | "intent" | "render" | "viewport";32/** Default preload delay in milliseconds */33defaultPreloadDelay?: number;34/** Default component used when route has no component */35defaultComponent?: RouteComponent;36/** Default error component for route errors */37defaultErrorComponent?: ErrorRouteComponent;38/** Default pending component shown during loading */39defaultPendingComponent?: RouteComponent;40/** Default not found component for 404 errors */41defaultNotFoundComponent?: NotFoundRouteComponent;42/** Minimum time to show pending component */43defaultPendingMinMs?: number;44/** Default time before showing pending component */45defaultPendingMs?: number;46/** Default stale time for route data */47defaultStaleTime?: number;48/** Default garbage collection time */49defaultGcTime?: number;50/** Whether routes are case sensitive */51caseSensitive?: boolean;52/** Trailing slash handling */53trailingSlash?: "always" | "never" | "preserve";54/** Enable structural sharing by default */55defaultStructuralSharing?: boolean;56/** Router wrapper component */57Wrap?: (props: { children: React.ReactNode }) => JSX.Element;58/** Inner router wrapper component */59InnerWrap?: (props: { children: React.ReactNode }) => JSX.Element;60/** Default error handler */61defaultOnCatch?: (error: Error, errorInfo: ErrorInfo) => void;62}63```6465**Usage Examples:**6667```typescript68import { createRouter, createBrowserHistory } from "@tanstack/react-router";6970// Basic router creation71const router = createRouter({72routeTree,73});7475// Router with custom configuration76const router = createRouter({77routeTree,78basepath: "/app",79defaultPreload: "intent",80defaultStaleTime: 5000,81caseSensitive: true,82trailingSlash: "never",83defaultComponent: () => <div>Loading...</div>,84defaultErrorComponent: ({ error }) => <div>Error: {error.message}</div>,85});8687// Router with custom history88const customHistory = createBrowserHistory();89const router = createRouter({90routeTree,91history: customHistory,92context: {93user: { id: "123", name: "John" },94theme: "dark",95},96});97```9899### Router Configuration100101Creates a router configuration object for advanced scenarios.102103```typescript { .api }104/**105* Create a router configuration object106* @param config - Router configuration107* @returns Router configuration object108*/109function createRouterConfig<TRouteTree extends AnyRoute>(110config: RouterConstructorOptions<TRouteTree>111): RouterConfig<TRouteTree>;112```113114### Router Class115116The main router class that manages navigation state, route matching, and lifecycle.117118```typescript { .api }119class Router<TRouteTree extends AnyRoute = AnyRoute> {120/** Router history instance */121history: RouterHistory;122/** Current router state */123state: RouterState<TRouteTree>;124/** Route tree */125routeTree: TRouteTree;126/** Router options */127options: RouterOptions;128129/**130* Navigate to a new location131* @param options - Navigation options132* @returns Promise that resolves when navigation completes133*/134navigate<TFrom extends RoutePaths<TRouteTree> = "/">(135options: NavigateOptions<TRouteTree, TFrom>136): Promise<void>;137138/**139* Build a location object from navigation options140* @param options - Navigation options141* @returns Parsed location object142*/143buildLocation<TFrom extends RoutePaths<TRouteTree> = "/">(144options: BuildLocationOptions<TRouteTree, TFrom>145): ParsedLocation;146147/**148* Invalidate all route matches149* @returns Promise that resolves when invalidation completes150*/151invalidate(): Promise<void>;152153/**154* Load a route by location155* @param location - Location to load156* @returns Promise that resolves when loading completes157*/158load(location?: ParsedLocation): Promise<void>;159160/**161* Preload a route162* @param options - Navigation options for route to preload163* @returns Promise that resolves when preloading completes164*/165preloadRoute<TFrom extends RoutePaths<TRouteTree> = "/">(166options: NavigateOptions<TRouteTree, TFrom>167): Promise<void>;168169/**170* Subscribe to router state changes171* @param fn - Listener function172* @returns Unsubscribe function173*/174subscribe(fn: (state: RouterState<TRouteTree>) => void): () => void;175176/**177* Match routes for a location178* @param location - Location to match179* @returns Array of route matches180*/181matchRoutes(location: ParsedLocation): RouteMatch[];182}183```184185## Types186187### Router State188189```typescript { .api }190interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {191/** Current location */192location: ParsedLocation;193/** Currently matched routes */194matches: RouteMatch[];195/** Pending matches during navigation */196pendingMatches?: RouteMatch[];197/** Whether router is in loading state */198isLoading: boolean;199/** Whether router is transitioning between routes */200isTransitioning: boolean;201/** Last updated timestamp */202lastUpdated: number;203/** Navigation status */204status: "idle" | "pending" | "success" | "error";205}206```207208### Router Events209210```typescript { .api }211interface RouterEvents {212onBeforeLoad: (event: {213router: Router;214fromLocation: ParsedLocation;215toLocation: ParsedLocation;216}) => void;217onLoad: (event: {218router: Router;219fromLocation: ParsedLocation;220toLocation: ParsedLocation;221}) => void;222onBeforeNavigate: (event: {223router: Router;224fromLocation: ParsedLocation;225toLocation: ParsedLocation;226}) => void;227onNavigate: (event: {228router: Router;229fromLocation: ParsedLocation;230toLocation: ParsedLocation;231}) => void;232}233```234235### History Types236237```typescript { .api }238interface RouterHistory {239/** Current location */240location: HistoryLocation;241/** Go back in history */242back(): void;243/** Go forward in history */244forward(): void;245/** Go to specific history entry */246go(n: number): void;247/** Push new location */248push(path: string, state?: any): void;249/** Replace current location */250replace(path: string, state?: any): void;251/** Create href for path */252createHref(path: string): string;253/** Subscribe to location changes */254subscribe(fn: (location: HistoryLocation) => void): () => void;255}256257interface HistoryLocation {258pathname: string;259search: string;260hash: string;261state?: any;262key?: string;263}264```