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

navigation-links.md docs/

1
# Navigation & Links
2
3
Navigation utilities, link components, and programmatic navigation with type-safe parameter handling, URL masking, and advanced navigation features.
4
5
## Capabilities
6
7
### Redirection
8
9
Create redirect responses for use in route loaders and actions.
10
11
```typescript { .api }
12
/**
13
* Create a redirect response
14
* @param options - Redirect configuration options
15
* @returns Redirect object for throwing from loaders/actions
16
*/
17
function redirect<TRouter extends AnyRouter = AnyRouter>(
18
options: RedirectOptions<TRouter>
19
): Redirect;
20
21
interface RedirectOptions<TRouter extends AnyRouter = AnyRouter> {
22
/** Redirect destination path */
23
to?: string;
24
/** Search parameters for redirect */
25
search?: Record<string, any> | ((current: any) => Record<string, any>);
26
/** Path parameters for redirect */
27
params?: Record<string, any>;
28
/** Hash fragment for redirect */
29
hash?: string | ((current: string) => string);
30
/** History state */
31
state?: any;
32
/** Use replace instead of push */
33
replace?: boolean;
34
/** HTTP status code (SSR) */
35
statusCode?: number;
36
/** HTTP headers (SSR) */
37
headers?: Record<string, string>;
38
}
39
40
/**
41
* Type guard for redirect objects
42
* @param obj - Object to check
43
* @returns Whether object is a redirect
44
*/
45
function isRedirect(obj: any): obj is Redirect;
46
47
interface Redirect {
48
code: "REDIRECT";
49
statusCode: number;
50
headers: Record<string, string>;
51
href: string;
52
}
53
```
54
55
**Usage Examples:**
56
57
```typescript
58
import { redirect } from "@tanstack/react-router";
59
60
// In route loader
61
const postRoute = createRoute({
62
path: "/posts/$postId",
63
loader: async ({ params, context }) => {
64
const post = await fetchPost(params.postId);
65
66
// Redirect if post not found
67
if (!post) {
68
throw redirect({
69
to: "/404",
70
statusCode: 404,
71
});
72
}
73
74
// Redirect if user doesn't have permission
75
if (!context.user.canViewPost(post)) {
76
throw redirect({
77
to: "/login",
78
search: { redirect: `/posts/${params.postId}` },
79
replace: true,
80
});
81
}
82
83
return { post };
84
},
85
});
86
87
// Conditional redirect in component
88
function ProtectedRoute() {
89
const { user } = useRouteContext();
90
91
if (!user) {
92
throw redirect({ to: "/login" });
93
}
94
95
return <Dashboard />;
96
}
97
```
98
99
### Link Utilities
100
101
Utilities for creating custom link components and validating link options.
102
103
```typescript { .api }
104
/**
105
* Create a custom link component with any element
106
* @param Comp - Base component to wrap with link functionality
107
* @returns Link component with router functionality
108
*/
109
function createLink<TComp extends React.ComponentType<any>>(
110
Comp: TComp
111
): LinkComponent<TComp>;
112
113
/**
114
* Validate and return link options with type safety
115
* @param options - Link options to validate
116
* @returns Validated link options
117
*/
118
function linkOptions<
119
TRouter extends AnyRouter = RegisteredRouter,
120
TFrom extends string = string,
121
TTo extends string | undefined = undefined,
122
TMaskFrom extends string = TFrom,
123
TMaskTo extends string = ""
124
>(
125
options: LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
126
): LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>;
127
128
type LinkComponent<TComp> = React.ForwardRefExoticComponent<
129
Omit<React.ComponentProps<TComp>, keyof LinkProps> & LinkProps
130
>;
131
```
132
133
**Usage Examples:**
134
135
```typescript
136
import { createLink, linkOptions } from "@tanstack/react-router";
137
138
// Create custom link with button
139
const ButtonLink = createLink("button");
140
141
function CustomNavigation() {
142
return (
143
<ButtonLink
144
to="/dashboard"
145
params={{ userId: "123" }}
146
activeProps={{ className: "active-button" }}
147
>
148
Dashboard
149
</ButtonLink>
150
);
151
}
152
153
// Create link with custom component
154
const CardLink = createLink(({ children, ...props }) => (
155
<div className="card" {...props}>
156
{children}
157
</div>
158
));
159
160
// Validate link options
161
function ValidatedLink({ to, ...options }) {
162
const validatedOptions = linkOptions({
163
to,
164
preload: "intent",
165
activeOptions: { exact: true },
166
...options,
167
});
168
169
return <Link {...validatedOptions} />;
170
}
171
```
172
173
### Navigation History
174
175
Create and manage browser history for navigation.
176
177
```typescript { .api }
178
/**
179
* Create a browser history instance
180
* @param options - Browser history options
181
* @returns Browser history instance
182
*/
183
function createBrowserHistory(options?: {
184
basename?: string;
185
window?: Window;
186
}): RouterHistory;
187
188
/**
189
* Create a hash history instance
190
* @param options - Hash history options
191
* @returns Hash history instance
192
*/
193
function createHashHistory(options?: {
194
basename?: string;
195
window?: Window;
196
}): RouterHistory;
197
198
/**
199
* Create a memory history instance for testing/SSR
200
* @param options - Memory history options
201
* @returns Memory history instance
202
*/
203
function createMemoryHistory(options?: {
204
initialEntries?: string[];
205
initialIndex?: number;
206
}): RouterHistory;
207
208
/**
209
* Create a history instance (base function)
210
* @param options - History options
211
* @returns History instance
212
*/
213
function createHistory(options: {
214
getLocation: () => HistoryLocation;
215
listener: (fn: () => void) => () => void;
216
pushState: (path: string, state?: any) => void;
217
replaceState: (path: string, state?: any) => void;
218
go: (n: number) => void;
219
back: () => void;
220
forward: () => void;
221
createHref?: (path: string) => string;
222
}): RouterHistory;
223
```
224
225
**Usage Examples:**
226
227
```typescript
228
import { createBrowserHistory, createMemoryHistory, createRouter } from "@tanstack/react-router";
229
230
// Browser history with basename
231
const history = createBrowserHistory({
232
basename: "/app",
233
});
234
235
const router = createRouter({
236
routeTree,
237
history,
238
});
239
240
// Memory history for testing
241
const testHistory = createMemoryHistory({
242
initialEntries: ["/", "/about", "/contact"],
243
initialIndex: 1, // Start at /about
244
});
245
246
// Hash history
247
const hashHistory = createHashHistory();
248
```
249
250
### Navigation Blocking
251
252
Utilities for blocking navigation under certain conditions.
253
254
```typescript { .api }
255
type BlockerFn = (args: {
256
fromLocation: ParsedLocation;
257
toLocation: ParsedLocation;
258
}) => boolean | Promise<boolean>;
259
260
type ShouldBlockFn = (
261
fromLocation: ParsedLocation,
262
toLocation: ParsedLocation
263
) => boolean;
264
```
265
266
### Route Matching Utilities
267
268
Utilities for checking route matches and building navigation options.
269
270
```typescript { .api }
271
/**
272
* Check if current location matches route pattern
273
* @param basepath - Base path
274
* @param currentPathname - Current pathname
275
* @param matchLocation - Location to match against
276
* @returns Match result or false
277
*/
278
function matchPathname(
279
basepath: string,
280
currentPathname: string,
281
matchLocation: MatchLocation
282
): MatchPathResult | false;
283
284
/**
285
* Match route by path pattern
286
* @param basepath - Base path
287
* @param currentPathname - Current pathname
288
* @param matchLocation - Location to match against
289
* @returns Match result or false
290
*/
291
function matchByPath(
292
basepath: string,
293
currentPathname: string,
294
matchLocation: MatchLocation
295
): MatchPathResult | false;
296
297
interface MatchLocation {
298
to: string;
299
params?: Record<string, any>;
300
search?: Record<string, any>;
301
hash?: string;
302
fuzzy?: boolean;
303
includeSearch?: boolean;
304
includeHash?: boolean;
305
}
306
307
interface MatchPathResult {
308
params: Record<string, string>;
309
}
310
```
311
312
### Build Navigation Functions
313
314
Utilities for building navigation and location objects.
315
316
```typescript { .api }
317
type BuildLocationFn<TRouter extends AnyRouter = AnyRouter> = <
318
TFrom extends RoutePaths<TRouter> = "/",
319
TTo extends string = "."
320
>(
321
opts: BuildLocationOptions<TRouter, TFrom, TTo>
322
) => ParsedLocation;
323
324
interface BuildLocationOptions<TRouter extends AnyRouter, TFrom extends RoutePaths<TRouter>, TTo extends string> {
325
to?: TTo;
326
from?: TFrom;
327
params?: Record<string, any>;
328
search?: Record<string, any> | ((prev: any) => Record<string, any>);
329
hash?: string | ((prev: string) => string);
330
state?: any;
331
}
332
333
type NavigateFn<TRouter extends AnyRouter = AnyRouter> = <
334
TFrom extends RoutePaths<TRouter> = "/",
335
TTo extends string = "."
336
>(
337
opts: NavigateOptions<TRouter, TFrom, TTo>
338
) => Promise<void>;
339
```
340
341
### Navigation Options Validation
342
343
Type-safe validation utilities for navigation options.
344
345
```typescript { .api }
346
type ValidateNavigateOptions<TRouter extends AnyRouter, TFrom extends string, TTo extends string> =
347
NavigateOptions<TRouter, TFrom, TTo>;
348
349
type ValidateNavigateOptionsArray<T> = T extends ReadonlyArray<infer U>
350
? U extends { to: infer TTo; from?: infer TFrom }
351
? TTo extends string
352
? TFrom extends string | undefined
353
? ValidateNavigateOptions<RegisteredRouter, TFrom extends string ? TFrom : "/", TTo>
354
: never
355
: never
356
: never
357
: never;
358
359
type ValidateRedirectOptions<TRouter extends AnyRouter, TFrom extends string, TTo extends string> =
360
RedirectOptions<TRouter>;
361
362
type ValidateRedirectOptionsArray<T> = T extends ReadonlyArray<infer U>
363
? U extends { to: infer TTo; from?: infer TFrom }
364
? TTo extends string
365
? TFrom extends string | undefined
366
? ValidateRedirectOptions<RegisteredRouter, TFrom extends string ? TFrom : "/", TTo>
367
: never
368
: never
369
: never
370
: never;
371
```
372
373
## Types
374
375
### Core Navigation Types
376
377
```typescript { .api }
378
interface NavigateOptions<
379
TRouter extends AnyRouter = AnyRouter,
380
TFrom extends RoutePaths<TRouter> = "/",
381
TTo extends string = "."
382
> {
383
/** Destination path */
384
to?: TTo;
385
/** Source path for relative navigation */
386
from?: TFrom;
387
/** Path parameters */
388
params?: MakeRouteMatch<TRouter, TFrom, TTo>["params"];
389
/** Search parameters */
390
search?: MakeRouteMatch<TRouter, TFrom, TTo>["search"] | ((prev: any) => any);
391
/** Hash fragment */
392
hash?: string | ((prev: string) => string);
393
/** History state */
394
state?: any;
395
/** Route mask options */
396
mask?: ToMaskOptions<TRouter, TFrom, TTo>;
397
/** Use replace instead of push */
398
replace?: boolean;
399
/** Reset scroll position */
400
resetScroll?: boolean;
401
/** Scroll hash target into view */
402
hashScrollIntoView?: boolean;
403
/** Wrap navigation in startTransition */
404
startTransition?: boolean;
405
/** Enable view transitions */
406
viewTransition?: boolean;
407
/** Ignore navigation blockers */
408
ignoreBlocker?: boolean;
409
}
410
411
interface LinkOptions<
412
TRouter extends AnyRouter = AnyRouter,
413
TFrom extends string = string,
414
TTo extends string | undefined = undefined,
415
TMaskFrom extends string = TFrom,
416
TMaskTo extends string = ""
417
> extends NavigateOptions<TRouter, TFrom, TTo> {
418
/** Props when link is active */
419
activeProps?:
420
| React.AnchorHTMLAttributes<HTMLAnchorElement>
421
| (() => React.AnchorHTMLAttributes<HTMLAnchorElement>);
422
/** Props when link is inactive */
423
inactiveProps?:
424
| React.AnchorHTMLAttributes<HTMLAnchorElement>
425
| (() => React.AnchorHTMLAttributes<HTMLAnchorElement>);
426
/** Active link matching options */
427
activeOptions?: ActiveLinkOptions;
428
/** Preload strategy */
429
preload?: false | "intent" | "render" | "viewport";
430
/** Preload delay in milliseconds */
431
preloadDelay?: number;
432
/** Disabled state */
433
disabled?: boolean;
434
}
435
436
interface ActiveLinkOptions {
437
/** Exact path matching */
438
exact?: boolean;
439
/** Include search parameters in matching */
440
includeSearch?: boolean;
441
/** Include hash in matching */
442
includeHash?: boolean;
443
}
444
```
445
446
### Route Masking Types
447
448
```typescript { .api }
449
interface ToMaskOptions<
450
TRouter extends AnyRouter = AnyRouter,
451
TFrom extends string = string,
452
TTo extends string = string
453
> {
454
/** Masked destination */
455
to?: string;
456
/** Masked parameters */
457
params?: Record<string, any>;
458
/** Masked search parameters */
459
search?: Record<string, any> | ((prev: any) => any);
460
/** Masked hash */
461
hash?: string | ((prev: string) => string);
462
/** Unmask on reload */
463
unmaskOnReload?: boolean;
464
}
465
466
interface RouteMask {
467
from: string;
468
to: string;
469
params?: Record<string, any>;
470
search?: Record<string, any>;
471
hash?: string;
472
unmaskOnReload?: boolean;
473
}
474
```
475
476
### Path Resolution Types
477
478
```typescript { .api }
479
type ToPathOption<
480
TRouter extends AnyRouter = AnyRouter,
481
TFrom extends RoutePaths<TRouter> = "/",
482
TTo extends string = string
483
> = TTo | RelativeToPathAutoComplete<TRouter, TFrom, TTo>;
484
485
type RelativeToPathAutoComplete<
486
TRouter extends AnyRouter,
487
TFrom extends string,
488
TTo extends string
489
> = TTo extends `..${infer _}`
490
? "../"
491
: TTo extends `./${infer _}`
492
? "./"
493
: TTo;
494
495
type AbsoluteToPath<TRouter extends AnyRouter, TTo extends string> = TTo;
496
497
type RelativeToPath<
498
TRouter extends AnyRouter,
499
TFrom extends string,
500
TTo extends string
501
> = TTo extends "."
502
? TFrom
503
: TTo extends `..${infer Rest}`
504
? RelativeToParentPath<TRouter, TFrom, Rest>
505
: TTo extends `./${infer Rest}`
506
? RelativeToCurrentPath<TRouter, TFrom, Rest>
507
: never;
508
```