Declarative routing for React web applications
npx @tessl/cli install tessl/npm-react-router-dom@7.8.00
# React Router DOM
1
2
React Router DOM is a compatibility package that serves as a migration bridge from React Router v6 to v7, providing a smooth upgrade path for web applications. This package primarily re-exports all functionality from the core react-router library while adding DOM-specific components like RouterProvider and HydratedRouter.
3
4
## Package Information
5
6
- **Package Name**: react-router-dom
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install react-router-dom`
10
11
## Core Imports
12
13
```typescript
14
import {
15
BrowserRouter,
16
Routes,
17
Route,
18
Link,
19
useNavigate,
20
useLocation,
21
RouterProvider
22
} from "react-router-dom";
23
```
24
25
For CommonJS:
26
27
```javascript
28
const {
29
BrowserRouter,
30
Routes,
31
Route,
32
Link,
33
useNavigate,
34
useLocation
35
} = require("react-router-dom");
36
```
37
38
## Basic Usage
39
40
```tsx
41
import React from "react";
42
import {
43
BrowserRouter,
44
Routes,
45
Route,
46
Link,
47
useNavigate,
48
useParams
49
} from "react-router-dom";
50
51
// Basic routing setup
52
function App() {
53
return (
54
<BrowserRouter>
55
<nav>
56
<Link to="/">Home</Link>
57
<Link to="/about">About</Link>
58
<Link to="/users/123">User Profile</Link>
59
</nav>
60
61
<Routes>
62
<Route path="/" element={<Home />} />
63
<Route path="/about" element={<About />} />
64
<Route path="/users/:id" element={<UserProfile />} />
65
</Routes>
66
</BrowserRouter>
67
);
68
}
69
70
// Component using hooks
71
function UserProfile() {
72
const { id } = useParams();
73
const navigate = useNavigate();
74
75
const handleBack = () => navigate(-1);
76
77
return (
78
<div>
79
<h1>User Profile: {id}</h1>
80
<button onClick={handleBack}>Go Back</button>
81
</div>
82
);
83
}
84
```
85
86
## Architecture
87
88
React Router DOM is built around several key architectural patterns:
89
90
- **Component-Based Routing**: Uses React components (`Route`, `Routes`) to declare routes declaratively
91
- **Re-export Layer**: Acts as a compatibility wrapper that re-exports the entire react-router API
92
- **DOM Integration**: Provides DOM-specific router components with React DOM integration
93
- **Hook-Based API**: Extensive hook system for accessing routing state and navigation
94
- **Data Loading**: Integrated data loading with loaders and actions for route-level data management
95
- **Server-Side Rendering**: Full SSR support with hydration and static generation capabilities
96
97
## Capabilities
98
99
### Router Components
100
101
Core router components for setting up routing in React applications, including browser-based routing, memory routing for testing, and static routing for SSR.
102
103
```typescript { .api }
104
function BrowserRouter(props: BrowserRouterProps): JSX.Element;
105
function HashRouter(props: HashRouterProps): JSX.Element;
106
function MemoryRouter(props: MemoryRouterProps): JSX.Element;
107
function Router(props: RouterProps): JSX.Element;
108
function RouterProvider(props: RouterProviderProps): JSX.Element;
109
110
interface BrowserRouterProps {
111
basename?: string;
112
children?: React.ReactNode;
113
window?: Window;
114
}
115
116
interface RouterProviderProps {
117
router: DataRouter;
118
unstable_onError?: (error: any, errorInfo: React.ErrorInfo) => void;
119
}
120
```
121
122
[Router Components](./router-components.md)
123
124
### Route Configuration
125
126
Route definition components and utilities for declaring application routes with support for nested routing, dynamic segments, and route data loading.
127
128
```typescript { .api }
129
function Routes(props: RoutesProps): JSX.Element;
130
function Route(props: RouteProps): JSX.Element;
131
function Outlet(props: OutletProps): JSX.Element;
132
133
interface RouteProps {
134
path?: string;
135
element?: React.ReactNode;
136
children?: React.ReactNode;
137
loader?: LoaderFunction;
138
action?: ActionFunction;
139
errorElement?: React.ReactNode;
140
shouldRevalidate?: ShouldRevalidateFunction;
141
}
142
143
interface LoaderFunctionArgs {
144
request: Request;
145
params: Params;
146
context?: any;
147
}
148
149
interface ActionFunctionArgs {
150
request: Request;
151
params: Params;
152
context?: any;
153
}
154
```
155
156
[Route Configuration](./route-configuration.md)
157
158
### Navigation Components
159
160
Components for creating navigation interfaces including links, forms, and programmatic navigation with support for active states and form handling.
161
162
```typescript { .api }
163
function Link(props: LinkProps): JSX.Element;
164
function NavLink(props: NavLinkProps): JSX.Element;
165
function Navigate(props: NavigateProps): JSX.Element;
166
function Form(props: FormProps): JSX.Element;
167
168
interface LinkProps {
169
to: To;
170
children?: React.ReactNode;
171
replace?: boolean;
172
state?: any;
173
preventScrollReset?: boolean;
174
relative?: RelativeRoutingType;
175
}
176
177
interface NavLinkProps extends Omit<LinkProps, 'className' | 'style'> {
178
className?: string | ((props: NavLinkRenderProps) => string);
179
style?: React.CSSProperties | ((props: NavLinkRenderProps) => React.CSSProperties);
180
end?: boolean;
181
caseSensitive?: boolean;
182
}
183
```
184
185
[Navigation Components](./navigation-components.md)
186
187
### Navigation Hooks
188
189
Hooks for accessing routing state and performing navigation operations, including location access, parameter extraction, and programmatic navigation.
190
191
```typescript { .api }
192
function useNavigate(): NavigateFunction;
193
function useLocation(): Location;
194
function useParams<K extends string = string>(): Readonly<Params<K>>;
195
function useSearchParams(defaultValue?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams];
196
197
interface NavigateFunction {
198
(to: To, options?: NavigateOptions): void;
199
(delta: number): void;
200
}
201
202
interface Location {
203
pathname: string;
204
search: string;
205
hash: string;
206
state: any;
207
key: string;
208
}
209
```
210
211
[Navigation Hooks](./navigation-hooks.md)
212
213
### Data Loading Hooks
214
215
Hooks for accessing route data including loader data, action data, and data fetching utilities with support for revalidation and optimistic updates.
216
217
```typescript { .api }
218
function useLoaderData<T = any>(): T;
219
function useActionData<T = any>(): T | undefined;
220
function useRouteLoaderData<T = any>(routeId: string): T | undefined;
221
function useFetcher<T = any>(): FetcherWithComponents<T>;
222
function useRevalidator(): Revalidator;
223
224
interface FetcherWithComponents<T> {
225
Form: React.ComponentType<FetcherFormProps>;
226
submit: FetcherSubmitFunction;
227
load: (href: string) => void;
228
data: T;
229
formData?: FormData;
230
state: "idle" | "loading" | "submitting";
231
}
232
```
233
234
[Data Loading Hooks](./data-loading-hooks.md)
235
236
### Router Creation
237
238
Functions for creating router instances programmatically with support for data loading, static generation, and memory-based routing for testing.
239
240
```typescript { .api }
241
function createBrowserRouter(
242
routes: RouteObject[],
243
opts?: DOMRouterOpts
244
): DataRouter;
245
246
function createHashRouter(
247
routes: RouteObject[],
248
opts?: DOMRouterOpts
249
): DataRouter;
250
251
function createMemoryRouter(
252
routes: RouteObject[],
253
opts?: MemoryRouterOpts
254
): DataRouter;
255
256
interface DOMRouterOpts {
257
basename?: string;
258
unstable_dataStrategy?: DataStrategyFunction;
259
unstable_patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
260
future?: Partial<Future>;
261
window?: Window;
262
}
263
```
264
265
[Router Creation](./router-creation.md)
266
267
### Server-Side Rendering
268
269
Components and utilities for server-side rendering including static routing, data loading on the server, and hydration support.
270
271
```typescript { .api }
272
function StaticRouter(props: StaticRouterProps): JSX.Element;
273
function StaticRouterProvider(props: StaticRouterProviderProps): JSX.Element;
274
function HydratedRouter(props: HydratedRouterProps): JSX.Element;
275
276
interface StaticRouterProps {
277
basename?: string;
278
children?: React.ReactNode;
279
location: Partial<Location> | string;
280
}
281
282
interface HydratedRouterProps {
283
unstable_getContext?: RouterInit["unstable_getContext"];
284
unstable_onError?: (error: any, errorInfo: React.ErrorInfo) => void;
285
}
286
```
287
288
[Server-Side Rendering](./server-side-rendering.md)
289
290
### Utilities
291
292
Path manipulation utilities, route matching functions, and data response helpers for advanced routing scenarios.
293
294
```typescript { .api }
295
function generatePath<T extends Record<string, any>>(
296
path: string,
297
params?: T
298
): string;
299
300
function matchPath<T extends Record<string, any>>(
301
pattern: PathPattern | string,
302
pathname: string
303
): PathMatch<T> | null;
304
305
function resolvePath(to: To, fromPathname?: string): Path;
306
307
function redirect(url: string, init?: number | ResponseInit): Response;
308
function data<T>(data: T, init?: number | ResponseInit): Response;
309
```
310
311
[Utilities](./utilities.md)
312
313
## Types
314
315
### Core Types
316
317
```typescript { .api }
318
type To = string | Partial<Path>;
319
320
interface Path {
321
pathname: string;
322
search: string;
323
hash: string;
324
}
325
326
interface Params<K extends string = string> {
327
readonly [key in K]: string | undefined;
328
}
329
330
type NavigationType = "POP" | "PUSH" | "REPLACE";
331
332
type RelativeRoutingType = "route" | "path";
333
```
334
335
### Route Types
336
337
```typescript { .api }
338
interface RouteObject {
339
path?: string;
340
index?: boolean;
341
children?: RouteObject[];
342
caseSensitive?: boolean;
343
id?: string;
344
loader?: LoaderFunction;
345
action?: ActionFunction;
346
element?: React.ReactNode | null;
347
errorElement?: React.ReactNode | null;
348
shouldRevalidate?: ShouldRevalidateFunction;
349
}
350
351
interface DataRouteObject extends RouteObject {
352
children?: DataRouteObject[];
353
id: string;
354
}
355
356
type LoaderFunction = (args: LoaderFunctionArgs) =>
357
| Promise<Response>
358
| Response
359
| Promise<any>
360
| any;
361
362
type ActionFunction = (args: ActionFunctionArgs) =>
363
| Promise<Response>
364
| Response
365
| Promise<any>
366
| any;
367
```
368
369
### Router Types
370
371
```typescript { .api }
372
interface DataRouter {
373
initialize(): void;
374
subscribe(subscriber: RouterSubscriber): () => void;
375
navigate(to: To, opts?: RouterNavigateOptions): Promise<void>;
376
fetch(key: string, routeId: string, href: string): Promise<void>;
377
revalidate(): void;
378
getRouteData(routeId: string): any;
379
dispose(): void;
380
state: RouterState;
381
}
382
383
interface RouterState {
384
historyAction: NavigationType;
385
location: Location;
386
matches: DataRouteMatch[];
387
initialized: boolean;
388
navigation: Navigation;
389
restoreScrollPosition: boolean | null;
390
preventScrollReset: boolean;
391
loaderData: Record<string, any>;
392
actionData: Record<string, any> | null;
393
errors: Record<string, any> | null;
394
fetchers: Map<string, Fetcher>;
395
blockers: Map<string, Blocker>;
396
}
397
```
398
399
### Navigation and State Types
400
401
```typescript { .api }
402
interface Navigation {
403
state: "idle" | "loading" | "submitting";
404
location?: Location;
405
formMethod?: FormMethod;
406
formAction?: string;
407
formEncType?: FormEncType;
408
formData?: FormData;
409
}
410
411
interface Blocker {
412
state: "unblocked" | "blocked" | "proceeding";
413
proceed?: () => void;
414
reset?: () => void;
415
location?: Location;
416
}
417
418
interface Fetcher {
419
state: "idle" | "loading" | "submitting";
420
data?: any;
421
formMethod?: FormMethod;
422
formAction?: string;
423
formEncType?: FormEncType;
424
formData?: FormData;
425
}
426
427
type FormMethod = "get" | "post" | "put" | "patch" | "delete";
428
type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data";
429
}
430
```