- 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
react-components.md docs/
1# React Components23Essential React components for router setup, navigation, route rendering, error handling, and SSR support. These components provide the UI layer for TanStack React Router functionality.45## Capabilities67### Router Provider89Main provider component that wraps the application and provides router context to all child components.1011```typescript { .api }12/**13* Router provider component that wraps the application14* @param props - Router provider props15* @returns JSX element providing router context16*/17function RouterProvider<TRouter extends AnyRouter, TDehydrated = unknown>(18props: RouterProps<TRouter, TDehydrated>19): JSX.Element;2021interface RouterProps<TRouter extends AnyRouter, TDehydrated = unknown> {22/** Router instance */23router: TRouter;24/** Dehydrated state for SSR */25dehydratedState?: TDehydrated;26/** Additional context */27context?: Partial<TRouter["options"]["context"]>;28/** Default component */29defaultComponent?: RouteComponent;30/** Default error component */31defaultErrorComponent?: ErrorRouteComponent;32/** Default pending component */33defaultPendingComponent?: RouteComponent;34/** Default not found component */35defaultNotFoundComponent?: NotFoundRouteComponent;36}37```3839**Usage Examples:**4041```typescript42import { RouterProvider, createRouter } from "@tanstack/react-router";4344function App() {45return (46<RouterProvider47router={router}48context={{49user: getCurrentUser(),50theme: "dark",51}}52/>53);54}5556// With SSR57function App({ dehydratedState }: { dehydratedState: any }) {58return (59<RouterProvider60router={router}61dehydratedState={dehydratedState}62defaultPendingComponent={() => <div>Loading...</div>}63/>64);65}66```6768### Router Context Provider6970Lower-level provider that only provides router context without rendering matches.7172```typescript { .api }73/**74* Router context provider without match rendering75* @param props - Context provider props76* @returns JSX element providing router context only77*/78function RouterContextProvider<TRouter extends AnyRouter>(79props: {80router: TRouter;81children: React.ReactNode;82}83): JSX.Element;84```8586### Navigation Link8788Navigation link component with active state management, preloading, and type-safe parameters.8990```typescript { .api }91/**92* Navigation link component with active state and preloading93* @param props - Link component props94* @returns JSX anchor element with router functionality95*/96function Link<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string>(97props: LinkProps<TRouter, TFrom>98): JSX.Element;99100interface LinkProps<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string>101extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {102/** Destination path */103to?: ToPathOption;104/** Source path for relative navigation */105from?: TFrom;106/** Path parameters */107params?: MakeRouteMatch["params"];108/** Search parameters */109search?: MakeRouteMatch["search"] | ((prev: any) => any);110/** Hash fragment */111hash?: string | ((prev: string) => string);112/** History state */113state?: any;114/** Route mask options */115mask?: ToMaskOptions;116/** Props when link is active */117activeProps?: React.AnchorHTMLAttributes<HTMLAnchorElement> | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>);118/** Props when link is inactive */119inactiveProps?: React.AnchorHTMLAttributes<HTMLAnchorElement> | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>);120/** Active matching options */121activeOptions?: ActiveLinkOptions;122/** Preload strategy */123preload?: false | "intent" | "render" | "viewport";124/** Preload delay in milliseconds */125preloadDelay?: number;126/** Use replace instead of push */127replace?: boolean;128/** Reset scroll position */129resetScroll?: boolean;130/** Scroll hash target into view */131hashScrollIntoView?: boolean;132/** Wrap navigation in startTransition */133startTransition?: boolean;134/** Enable view transitions */135viewTransition?: boolean;136/** Ignore navigation blockers */137ignoreBlocker?: boolean;138/** Child content */139children?: React.ReactNode | ((state: { isActive: boolean; isTransitioning: boolean }) => React.ReactNode);140}141```142143**Usage Examples:**144145```typescript146import { Link } from "@tanstack/react-router";147148// Basic link149<Link to="/about">About</Link>150151// Link with parameters152<Link to="/posts/$postId" params={{ postId: "123" }}>153View Post154</Link>155156// Link with search params and active styles157<Link158to="/search"159search={{ q: "react", page: 1 }}160activeProps={{ className: "active" }}161preload="intent"162>163Search164</Link>165166// Link with render prop children167<Link to="/profile">168{({ isActive, isTransitioning }) => (169<span className={isActive ? "active" : ""}>170Profile {isTransitioning && "..."}171</span>172)}173</Link>174```175176### Route Rendering Components177178Components for rendering route matches and providing outlet functionality.179180```typescript { .api }181/**182* Renders a specific route match with error boundaries and suspense183* @param props - Match component props184* @returns JSX element rendering the route match185*/186function Match(props: { matchId: string }): JSX.Element;187188/**189* Renders child route matches, acts as placeholder for nested routes190* @returns JSX element rendering child routes191*/192function Outlet(): JSX.Element;193194/**195* Root component that renders all active route matches196* @returns JSX element rendering all matches197*/198function Matches(): JSX.Element;199```200201**Usage Examples:**202203```typescript204import { Match, Outlet, Matches } from "@tanstack/react-router";205206// In root route component207function RootLayout() {208return (209<div>210<nav>Navigation</nav>211<main>212<Outlet />213</main>214</div>215);216}217218// Custom match rendering219function CustomRenderer() {220return (221<div>222<Match matchId="specific-route-id" />223</div>224);225}226227// Complete match rendering228function App() {229return <Matches />;230}231```232233### Conditional Rendering234235Component for conditionally rendering based on route matches.236237```typescript { .api }238/**239* Conditionally renders children based on route match240* @param props - MatchRoute component props241* @returns JSX element or null based on match242*/243function MatchRoute<TRouter extends AnyRouter = RegisteredRouter>(244props: MakeMatchRouteOptions<TRouter> & {245children?: React.ReactNode | ((params: any) => React.ReactNode);246}247): JSX.Element | null;248```249250**Usage Examples:**251252```typescript253import { MatchRoute } from "@tanstack/react-router";254255// Show content only on specific route256<MatchRoute to="/dashboard" params={{ tab: "analytics" }}>257<AnalyticsDashboard />258</MatchRoute>259260// With render prop261<MatchRoute to="/posts/$postId">262{(params) => <PostDetails postId={params.postId} />}263</MatchRoute>264```265266### Navigation Components267268Components for programmatic navigation.269270```typescript { .api }271/**272* Imperatively navigates when rendered273* @param props - Navigate component props274* @returns null (triggers navigation side effect)275*/276function Navigate<TRouter extends AnyRouter = RegisteredRouter>(277props: NavigateOptions<TRouter>278): null;279```280281**Usage Examples:**282283```typescript284import { Navigate } from "@tanstack/react-router";285286function LoginRedirect() {287if (!user) {288return <Navigate to="/login" replace />;289}290return <Dashboard />;291}292```293294### Error Handling Components295296Components for handling errors and not found states.297298```typescript { .api }299/**300* Error boundary for catching and handling errors301* @param props - CatchBoundary component props302* @returns JSX element with error boundary functionality303*/304function CatchBoundary(props: CatchBoundaryProps): JSX.Element;305306interface CatchBoundaryProps {307/** Function to get reset key for boundary reset */308getResetKey: () => string | number;309/** Child components */310children: React.ReactNode;311/** Error component to render */312errorComponent?: ErrorRouteComponent;313/** Error handler callback */314onCatch?: (error: Error, errorInfo: React.ErrorInfo) => void;315}316317/**318* Default error display component319* @param props - Error component props320* @returns JSX element displaying error321*/322function ErrorComponent(props: { error: any }): JSX.Element;323324/**325* Boundary specifically for handling not found errors326* @param props - CatchNotFound component props327* @returns JSX element with not found error handling328*/329function CatchNotFound(props: {330fallback?: (error: NotFoundError) => React.ReactElement;331onCatch?: (error: Error, errorInfo: React.ErrorInfo) => void;332children: React.ReactNode;333}): JSX.Element;334335/**336* Default global not found component337* @returns JSX element for 404 errors338*/339function DefaultGlobalNotFound(): JSX.Element;340```341342**Usage Examples:**343344```typescript345import { CatchBoundary, ErrorComponent, CatchNotFound } from "@tanstack/react-router";346347// Error boundary with custom error component348<CatchBoundary349getResetKey={() => window.location.pathname}350errorComponent={({ error, reset }) => (351<div>352<h2>Something went wrong</h2>353<p>{error.message}</p>354<button onClick={reset}>Try again</button>355</div>356)}357onCatch={(error, errorInfo) => {358console.error("Route error:", error, errorInfo);359}}360>361<App />362</CatchBoundary>363364// Not found boundary365<CatchNotFound366fallback={(error) => <div>Page not found: {error.message}</div>}367>368<Routes />369</CatchNotFound>370```371372### Async Components373374Components for handling asynchronous operations and promises.375376```typescript { .api }377/**378* Suspense-based promise resolution component379* @param props - Await component props380* @returns JSX element with promise handling381*/382function Await<T>(props: AwaitOptions<T> & {383fallback?: React.ReactNode;384children: (result: T) => React.ReactNode;385}): JSX.Element;386387interface AwaitOptions<T> {388/** Promise to await */389promise: Promise<T>;390}391```392393**Usage Examples:**394395```typescript396import { Await, defer } from "@tanstack/react-router";397398// In route loader399const Route = createRoute({400path: "/posts",401loader: () => ({402posts: defer(fetchPosts()),403}),404component: PostsPage,405});406407function PostsPage() {408const { posts } = Route.useLoaderData();409410return (411<Await promise={posts} fallback={<div>Loading posts...</div>}>412{(posts) => (413<div>414{posts.map(post => <PostCard key={post.id} post={post} />)}415</div>416)}417</Await>418);419}420```421422### Navigation Blocking423424Components for blocking navigation based on conditions.425426```typescript { .api }427/**428* Blocks navigation based on conditions429* @param props - Block component props430* @returns JSX element or null431*/432function Block<TRouter extends AnyRouter = RegisteredRouter>(433props: BlockProps<TRouter>434): JSX.Element | null;435436interface BlockProps<TRouter extends AnyRouter = RegisteredRouter> {437/** Function to determine if navigation should be blocked */438shouldBlockFn: ShouldBlockFn;439/** Enable beforeunload blocking */440enableBeforeUnload?: boolean | (() => boolean);441/** Disable the blocker */442disabled?: boolean;443/** Use resolver pattern */444withResolver?: boolean;445/** Child content */446children?: React.ReactNode | ((resolver: any) => React.ReactNode);447}448```449450### Client-Side Only Components451452Components that only render on the client side.453454```typescript { .api }455/**456* Only renders children on client side457* @param props - ClientOnly component props458* @returns JSX element or fallback459*/460function ClientOnly(props: {461children: React.ReactNode;462fallback?: React.ReactNode;463}): JSX.Element;464```465466### Utility Components467468Utility components for safe rendering and common patterns.469470```typescript { .api }471/**472* Safe fragment component for wrapping children473* @param props - Component props with children474* @returns JSX fragment with children475*/476function SafeFragment(props: { children?: React.ReactNode }): JSX.Element;477```478479**Usage Examples:**480481```typescript482import { SafeFragment } from "@tanstack/react-router";483484function MyComponent() {485return (486<SafeFragment>487<div>Child 1</div>488<div>Child 2</div>489</SafeFragment>490);491}492493// Useful for conditional rendering494function ConditionalContent({ items }: { items: string[] }) {495if (items.length === 0) return null;496497return (498<SafeFragment>499{items.map((item, index) => (500<div key={index}>{item}</div>501))}502</SafeFragment>503);504}505```506507### SSR Components508509Components for server-side rendering and asset management.510511```typescript { .api }512/**513* Renders route-specific and manifest scripts (SSR)514* @returns JSX element with script tags515*/516function Scripts(): JSX.Element;517518/**519* Renders various HTML assets (scripts, styles, meta, etc.)520* @param props - Asset component props521* @returns JSX element with asset tags522*/523function Asset(props: RouterManagedTag & { nonce?: string }): JSX.Element;524525/**526* Renders head content from route matches527* @returns JSX element with head content528*/529function HeadContent(): JSX.Element;530531/**532* Ensures scripts are only rendered once533* @param props - Script attributes534* @returns JSX script element535*/536function ScriptOnce(props: React.ScriptHTMLAttributes<HTMLScriptElement>): JSX.Element;537```538539### Lazy Loading Components540541Utilities for creating lazy-loaded route components with automatic code splitting.542543```typescript { .api }544/**545* Create a lazy route component with dynamic import546* @param importer - Function that returns a dynamic import promise547* @param exportName - Named export to use (defaults to 'default')548* @returns Lazy component with preload capability549*/550function lazyRouteComponent<551T extends Record<string, any>,552TKey extends keyof T = 'default'553>(554importer: () => Promise<T>,555exportName?: TKey556): T[TKey] extends (props: infer TProps) => any557? AsyncRouteComponent<TProps>558: never;559560/**561* Create a lazy component wrapper562* @param fn - Function that returns a dynamic import promise563* @returns Lazy component564*/565function lazyFn<T>(fn: () => Promise<T>): LazyComponent<T>;566567/**568* Component types available for routes569* Array of valid component type strings570*/571declare const componentTypes: string[];572```573574**Usage Examples:**575576```typescript577import { lazyRouteComponent } from "@tanstack/react-router";578579// Lazy load a default export580const LazyDashboard = lazyRouteComponent(() => import("./Dashboard"));581582// Lazy load a named export583const LazySettings = lazyRouteComponent(584() => import("./SettingsComponents"),585"SettingsPage"586);587588// Use in route definition589const dashboardRoute = createRoute({590path: "/dashboard",591component: LazyDashboard,592});593594// Preload component595LazyDashboard.preload();596597// With error handling598const LazyComponent = lazyRouteComponent(() =>599import("./Component").catch(error => {600console.error("Failed to load component:", error);601throw error;602})603);604```605606### Scroll Management607608Components for managing scroll position and restoration.609610```typescript { .api }611/**612* Handles scroll position restoration613* @param props - ScrollRestoration component props614* @returns null (manages scroll as side effect)615*/616function ScrollRestoration(props: {617getKey?: (location: ParsedLocation) => string;618}): null;619```620621## Types622623### Component Props Types624625```typescript { .api }626interface ActiveLinkOptions {627/** Exact path matching */628exact?: boolean;629/** Include hash in matching */630includeHash?: boolean;631/** Include search in matching */632includeSearch?: boolean;633}634635interface RouterManagedTag {636tag: "script" | "style" | "link" | "meta";637attrs?: Record<string, string>;638children?: string;639}640```