npm-tanstack--react-router

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 Components
2
3
Essential React components for router setup, navigation, route rendering, error handling, and SSR support. These components provide the UI layer for TanStack React Router functionality.
4
5
## Capabilities
6
7
### Router Provider
8
9
Main provider component that wraps the application and provides router context to all child components.
10
11
```typescript { .api }
12
/**
13
* Router provider component that wraps the application
14
* @param props - Router provider props
15
* @returns JSX element providing router context
16
*/
17
function RouterProvider<TRouter extends AnyRouter, TDehydrated = unknown>(
18
props: RouterProps<TRouter, TDehydrated>
19
): JSX.Element;
20
21
interface RouterProps<TRouter extends AnyRouter, TDehydrated = unknown> {
22
/** Router instance */
23
router: TRouter;
24
/** Dehydrated state for SSR */
25
dehydratedState?: TDehydrated;
26
/** Additional context */
27
context?: Partial<TRouter["options"]["context"]>;
28
/** Default component */
29
defaultComponent?: RouteComponent;
30
/** Default error component */
31
defaultErrorComponent?: ErrorRouteComponent;
32
/** Default pending component */
33
defaultPendingComponent?: RouteComponent;
34
/** Default not found component */
35
defaultNotFoundComponent?: NotFoundRouteComponent;
36
}
37
```
38
39
**Usage Examples:**
40
41
```typescript
42
import { RouterProvider, createRouter } from "@tanstack/react-router";
43
44
function App() {
45
return (
46
<RouterProvider
47
router={router}
48
context={{
49
user: getCurrentUser(),
50
theme: "dark",
51
}}
52
/>
53
);
54
}
55
56
// With SSR
57
function App({ dehydratedState }: { dehydratedState: any }) {
58
return (
59
<RouterProvider
60
router={router}
61
dehydratedState={dehydratedState}
62
defaultPendingComponent={() => <div>Loading...</div>}
63
/>
64
);
65
}
66
```
67
68
### Router Context Provider
69
70
Lower-level provider that only provides router context without rendering matches.
71
72
```typescript { .api }
73
/**
74
* Router context provider without match rendering
75
* @param props - Context provider props
76
* @returns JSX element providing router context only
77
*/
78
function RouterContextProvider<TRouter extends AnyRouter>(
79
props: {
80
router: TRouter;
81
children: React.ReactNode;
82
}
83
): JSX.Element;
84
```
85
86
### Navigation Link
87
88
Navigation link component with active state management, preloading, and type-safe parameters.
89
90
```typescript { .api }
91
/**
92
* Navigation link component with active state and preloading
93
* @param props - Link component props
94
* @returns JSX anchor element with router functionality
95
*/
96
function Link<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string>(
97
props: LinkProps<TRouter, TFrom>
98
): JSX.Element;
99
100
interface LinkProps<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string>
101
extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
102
/** Destination path */
103
to?: ToPathOption;
104
/** Source path for relative navigation */
105
from?: TFrom;
106
/** Path parameters */
107
params?: MakeRouteMatch["params"];
108
/** Search parameters */
109
search?: MakeRouteMatch["search"] | ((prev: any) => any);
110
/** Hash fragment */
111
hash?: string | ((prev: string) => string);
112
/** History state */
113
state?: any;
114
/** Route mask options */
115
mask?: ToMaskOptions;
116
/** Props when link is active */
117
activeProps?: React.AnchorHTMLAttributes<HTMLAnchorElement> | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>);
118
/** Props when link is inactive */
119
inactiveProps?: React.AnchorHTMLAttributes<HTMLAnchorElement> | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>);
120
/** Active matching options */
121
activeOptions?: ActiveLinkOptions;
122
/** Preload strategy */
123
preload?: false | "intent" | "render" | "viewport";
124
/** Preload delay in milliseconds */
125
preloadDelay?: number;
126
/** Use replace instead of push */
127
replace?: boolean;
128
/** Reset scroll position */
129
resetScroll?: boolean;
130
/** Scroll hash target into view */
131
hashScrollIntoView?: boolean;
132
/** Wrap navigation in startTransition */
133
startTransition?: boolean;
134
/** Enable view transitions */
135
viewTransition?: boolean;
136
/** Ignore navigation blockers */
137
ignoreBlocker?: boolean;
138
/** Child content */
139
children?: React.ReactNode | ((state: { isActive: boolean; isTransitioning: boolean }) => React.ReactNode);
140
}
141
```
142
143
**Usage Examples:**
144
145
```typescript
146
import { Link } from "@tanstack/react-router";
147
148
// Basic link
149
<Link to="/about">About</Link>
150
151
// Link with parameters
152
<Link to="/posts/$postId" params={{ postId: "123" }}>
153
View Post
154
</Link>
155
156
// Link with search params and active styles
157
<Link
158
to="/search"
159
search={{ q: "react", page: 1 }}
160
activeProps={{ className: "active" }}
161
preload="intent"
162
>
163
Search
164
</Link>
165
166
// Link with render prop children
167
<Link to="/profile">
168
{({ isActive, isTransitioning }) => (
169
<span className={isActive ? "active" : ""}>
170
Profile {isTransitioning && "..."}
171
</span>
172
)}
173
</Link>
174
```
175
176
### Route Rendering Components
177
178
Components for rendering route matches and providing outlet functionality.
179
180
```typescript { .api }
181
/**
182
* Renders a specific route match with error boundaries and suspense
183
* @param props - Match component props
184
* @returns JSX element rendering the route match
185
*/
186
function Match(props: { matchId: string }): JSX.Element;
187
188
/**
189
* Renders child route matches, acts as placeholder for nested routes
190
* @returns JSX element rendering child routes
191
*/
192
function Outlet(): JSX.Element;
193
194
/**
195
* Root component that renders all active route matches
196
* @returns JSX element rendering all matches
197
*/
198
function Matches(): JSX.Element;
199
```
200
201
**Usage Examples:**
202
203
```typescript
204
import { Match, Outlet, Matches } from "@tanstack/react-router";
205
206
// In root route component
207
function RootLayout() {
208
return (
209
<div>
210
<nav>Navigation</nav>
211
<main>
212
<Outlet />
213
</main>
214
</div>
215
);
216
}
217
218
// Custom match rendering
219
function CustomRenderer() {
220
return (
221
<div>
222
<Match matchId="specific-route-id" />
223
</div>
224
);
225
}
226
227
// Complete match rendering
228
function App() {
229
return <Matches />;
230
}
231
```
232
233
### Conditional Rendering
234
235
Component for conditionally rendering based on route matches.
236
237
```typescript { .api }
238
/**
239
* Conditionally renders children based on route match
240
* @param props - MatchRoute component props
241
* @returns JSX element or null based on match
242
*/
243
function MatchRoute<TRouter extends AnyRouter = RegisteredRouter>(
244
props: MakeMatchRouteOptions<TRouter> & {
245
children?: React.ReactNode | ((params: any) => React.ReactNode);
246
}
247
): JSX.Element | null;
248
```
249
250
**Usage Examples:**
251
252
```typescript
253
import { MatchRoute } from "@tanstack/react-router";
254
255
// Show content only on specific route
256
<MatchRoute to="/dashboard" params={{ tab: "analytics" }}>
257
<AnalyticsDashboard />
258
</MatchRoute>
259
260
// With render prop
261
<MatchRoute to="/posts/$postId">
262
{(params) => <PostDetails postId={params.postId} />}
263
</MatchRoute>
264
```
265
266
### Navigation Components
267
268
Components for programmatic navigation.
269
270
```typescript { .api }
271
/**
272
* Imperatively navigates when rendered
273
* @param props - Navigate component props
274
* @returns null (triggers navigation side effect)
275
*/
276
function Navigate<TRouter extends AnyRouter = RegisteredRouter>(
277
props: NavigateOptions<TRouter>
278
): null;
279
```
280
281
**Usage Examples:**
282
283
```typescript
284
import { Navigate } from "@tanstack/react-router";
285
286
function LoginRedirect() {
287
if (!user) {
288
return <Navigate to="/login" replace />;
289
}
290
return <Dashboard />;
291
}
292
```
293
294
### Error Handling Components
295
296
Components for handling errors and not found states.
297
298
```typescript { .api }
299
/**
300
* Error boundary for catching and handling errors
301
* @param props - CatchBoundary component props
302
* @returns JSX element with error boundary functionality
303
*/
304
function CatchBoundary(props: CatchBoundaryProps): JSX.Element;
305
306
interface CatchBoundaryProps {
307
/** Function to get reset key for boundary reset */
308
getResetKey: () => string | number;
309
/** Child components */
310
children: React.ReactNode;
311
/** Error component to render */
312
errorComponent?: ErrorRouteComponent;
313
/** Error handler callback */
314
onCatch?: (error: Error, errorInfo: React.ErrorInfo) => void;
315
}
316
317
/**
318
* Default error display component
319
* @param props - Error component props
320
* @returns JSX element displaying error
321
*/
322
function ErrorComponent(props: { error: any }): JSX.Element;
323
324
/**
325
* Boundary specifically for handling not found errors
326
* @param props - CatchNotFound component props
327
* @returns JSX element with not found error handling
328
*/
329
function CatchNotFound(props: {
330
fallback?: (error: NotFoundError) => React.ReactElement;
331
onCatch?: (error: Error, errorInfo: React.ErrorInfo) => void;
332
children: React.ReactNode;
333
}): JSX.Element;
334
335
/**
336
* Default global not found component
337
* @returns JSX element for 404 errors
338
*/
339
function DefaultGlobalNotFound(): JSX.Element;
340
```
341
342
**Usage Examples:**
343
344
```typescript
345
import { CatchBoundary, ErrorComponent, CatchNotFound } from "@tanstack/react-router";
346
347
// Error boundary with custom error component
348
<CatchBoundary
349
getResetKey={() => window.location.pathname}
350
errorComponent={({ 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
)}
357
onCatch={(error, errorInfo) => {
358
console.error("Route error:", error, errorInfo);
359
}}
360
>
361
<App />
362
</CatchBoundary>
363
364
// Not found boundary
365
<CatchNotFound
366
fallback={(error) => <div>Page not found: {error.message}</div>}
367
>
368
<Routes />
369
</CatchNotFound>
370
```
371
372
### Async Components
373
374
Components for handling asynchronous operations and promises.
375
376
```typescript { .api }
377
/**
378
* Suspense-based promise resolution component
379
* @param props - Await component props
380
* @returns JSX element with promise handling
381
*/
382
function Await<T>(props: AwaitOptions<T> & {
383
fallback?: React.ReactNode;
384
children: (result: T) => React.ReactNode;
385
}): JSX.Element;
386
387
interface AwaitOptions<T> {
388
/** Promise to await */
389
promise: Promise<T>;
390
}
391
```
392
393
**Usage Examples:**
394
395
```typescript
396
import { Await, defer } from "@tanstack/react-router";
397
398
// In route loader
399
const Route = createRoute({
400
path: "/posts",
401
loader: () => ({
402
posts: defer(fetchPosts()),
403
}),
404
component: PostsPage,
405
});
406
407
function PostsPage() {
408
const { posts } = Route.useLoaderData();
409
410
return (
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
```
421
422
### Navigation Blocking
423
424
Components for blocking navigation based on conditions.
425
426
```typescript { .api }
427
/**
428
* Blocks navigation based on conditions
429
* @param props - Block component props
430
* @returns JSX element or null
431
*/
432
function Block<TRouter extends AnyRouter = RegisteredRouter>(
433
props: BlockProps<TRouter>
434
): JSX.Element | null;
435
436
interface BlockProps<TRouter extends AnyRouter = RegisteredRouter> {
437
/** Function to determine if navigation should be blocked */
438
shouldBlockFn: ShouldBlockFn;
439
/** Enable beforeunload blocking */
440
enableBeforeUnload?: boolean | (() => boolean);
441
/** Disable the blocker */
442
disabled?: boolean;
443
/** Use resolver pattern */
444
withResolver?: boolean;
445
/** Child content */
446
children?: React.ReactNode | ((resolver: any) => React.ReactNode);
447
}
448
```
449
450
### Client-Side Only Components
451
452
Components that only render on the client side.
453
454
```typescript { .api }
455
/**
456
* Only renders children on client side
457
* @param props - ClientOnly component props
458
* @returns JSX element or fallback
459
*/
460
function ClientOnly(props: {
461
children: React.ReactNode;
462
fallback?: React.ReactNode;
463
}): JSX.Element;
464
```
465
466
### Utility Components
467
468
Utility components for safe rendering and common patterns.
469
470
```typescript { .api }
471
/**
472
* Safe fragment component for wrapping children
473
* @param props - Component props with children
474
* @returns JSX fragment with children
475
*/
476
function SafeFragment(props: { children?: React.ReactNode }): JSX.Element;
477
```
478
479
**Usage Examples:**
480
481
```typescript
482
import { SafeFragment } from "@tanstack/react-router";
483
484
function MyComponent() {
485
return (
486
<SafeFragment>
487
<div>Child 1</div>
488
<div>Child 2</div>
489
</SafeFragment>
490
);
491
}
492
493
// Useful for conditional rendering
494
function ConditionalContent({ items }: { items: string[] }) {
495
if (items.length === 0) return null;
496
497
return (
498
<SafeFragment>
499
{items.map((item, index) => (
500
<div key={index}>{item}</div>
501
))}
502
</SafeFragment>
503
);
504
}
505
```
506
507
### SSR Components
508
509
Components for server-side rendering and asset management.
510
511
```typescript { .api }
512
/**
513
* Renders route-specific and manifest scripts (SSR)
514
* @returns JSX element with script tags
515
*/
516
function Scripts(): JSX.Element;
517
518
/**
519
* Renders various HTML assets (scripts, styles, meta, etc.)
520
* @param props - Asset component props
521
* @returns JSX element with asset tags
522
*/
523
function Asset(props: RouterManagedTag & { nonce?: string }): JSX.Element;
524
525
/**
526
* Renders head content from route matches
527
* @returns JSX element with head content
528
*/
529
function HeadContent(): JSX.Element;
530
531
/**
532
* Ensures scripts are only rendered once
533
* @param props - Script attributes
534
* @returns JSX script element
535
*/
536
function ScriptOnce(props: React.ScriptHTMLAttributes<HTMLScriptElement>): JSX.Element;
537
```
538
539
### Lazy Loading Components
540
541
Utilities for creating lazy-loaded route components with automatic code splitting.
542
543
```typescript { .api }
544
/**
545
* Create a lazy route component with dynamic import
546
* @param importer - Function that returns a dynamic import promise
547
* @param exportName - Named export to use (defaults to 'default')
548
* @returns Lazy component with preload capability
549
*/
550
function lazyRouteComponent<
551
T extends Record<string, any>,
552
TKey extends keyof T = 'default'
553
>(
554
importer: () => Promise<T>,
555
exportName?: TKey
556
): T[TKey] extends (props: infer TProps) => any
557
? AsyncRouteComponent<TProps>
558
: never;
559
560
/**
561
* Create a lazy component wrapper
562
* @param fn - Function that returns a dynamic import promise
563
* @returns Lazy component
564
*/
565
function lazyFn<T>(fn: () => Promise<T>): LazyComponent<T>;
566
567
/**
568
* Component types available for routes
569
* Array of valid component type strings
570
*/
571
declare const componentTypes: string[];
572
```
573
574
**Usage Examples:**
575
576
```typescript
577
import { lazyRouteComponent } from "@tanstack/react-router";
578
579
// Lazy load a default export
580
const LazyDashboard = lazyRouteComponent(() => import("./Dashboard"));
581
582
// Lazy load a named export
583
const LazySettings = lazyRouteComponent(
584
() => import("./SettingsComponents"),
585
"SettingsPage"
586
);
587
588
// Use in route definition
589
const dashboardRoute = createRoute({
590
path: "/dashboard",
591
component: LazyDashboard,
592
});
593
594
// Preload component
595
LazyDashboard.preload();
596
597
// With error handling
598
const LazyComponent = lazyRouteComponent(() =>
599
import("./Component").catch(error => {
600
console.error("Failed to load component:", error);
601
throw error;
602
})
603
);
604
```
605
606
### Scroll Management
607
608
Components for managing scroll position and restoration.
609
610
```typescript { .api }
611
/**
612
* Handles scroll position restoration
613
* @param props - ScrollRestoration component props
614
* @returns null (manages scroll as side effect)
615
*/
616
function ScrollRestoration(props: {
617
getKey?: (location: ParsedLocation) => string;
618
}): null;
619
```
620
621
## Types
622
623
### Component Props Types
624
625
```typescript { .api }
626
interface ActiveLinkOptions {
627
/** Exact path matching */
628
exact?: boolean;
629
/** Include hash in matching */
630
includeHash?: boolean;
631
/** Include search in matching */
632
includeSearch?: boolean;
633
}
634
635
interface RouterManagedTag {
636
tag: "script" | "style" | "link" | "meta";
637
attrs?: Record<string, string>;
638
children?: string;
639
}
640
```