0
# Navigation Components
1
2
Components for creating navigation interfaces including links, forms, and programmatic navigation with support for active states and form handling.
3
4
## Capabilities
5
6
### Link
7
8
Creates navigation links that update the URL without full page reloads.
9
10
```typescript { .api }
11
/**
12
* Navigation link component for client-side routing
13
* @param props - Link configuration including destination and options
14
* @returns Anchor element with router navigation
15
*/
16
function Link(props: LinkProps): JSX.Element;
17
18
interface LinkProps {
19
/** Navigation destination */
20
to: To;
21
/** Child content to render inside the link */
22
children?: React.ReactNode;
23
/** Replace current entry instead of pushing new entry */
24
replace?: boolean;
25
/** State object to pass with navigation */
26
state?: any;
27
/** Prevent default scroll reset behavior */
28
preventScrollReset?: boolean;
29
/** Enable relative path resolution */
30
relative?: RelativeRoutingType;
31
/** Standard anchor props */
32
target?: React.HTMLAttributeAnchorTarget;
33
className?: string;
34
style?: React.CSSProperties;
35
onClick?: React.MouseEventHandler<HTMLAnchorElement>;
36
}
37
38
type To = string | Partial<Path>;
39
40
interface Path {
41
/** URL pathname */
42
pathname: string;
43
/** URL search parameters */
44
search: string;
45
/** URL hash fragment */
46
hash: string;
47
}
48
49
type RelativeRoutingType = "route" | "path";
50
```
51
52
**Usage Examples:**
53
54
```tsx
55
import { Link } from "react-router-dom";
56
57
// Basic link
58
<Link to="/about">About Us</Link>
59
60
// Link with state
61
<Link to="/user" state={{ from: "dashboard" }}>
62
User Profile
63
</Link>
64
65
// Link with path object
66
<Link to={{ pathname: "/search", search: "?q=react" }}>
67
Search React
68
</Link>
69
70
// Replace navigation (no back button)
71
<Link to="/login" replace>
72
Login
73
</Link>
74
```
75
76
### NavLink
77
78
Enhanced link component that knows whether it's "active" based on current location.
79
80
```typescript { .api }
81
/**
82
* Navigation link with active state awareness
83
* @param props - NavLink configuration with active state handling
84
* @returns Link component with active state styling support
85
*/
86
function NavLink(props: NavLinkProps): JSX.Element;
87
88
interface NavLinkProps extends Omit<LinkProps, 'className' | 'style'> {
89
/** Class name or function returning class name based on active state */
90
className?: string | ((props: NavLinkRenderProps) => string);
91
/** Style object or function returning styles based on active state */
92
style?: React.CSSProperties | ((props: NavLinkRenderProps) => React.CSSProperties);
93
/** Child content or function returning content based on active state */
94
children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);
95
/** Only active when location matches exactly */
96
end?: boolean;
97
/** Enable case-sensitive matching */
98
caseSensitive?: boolean;
99
}
100
101
interface NavLinkRenderProps {
102
/** True if the link matches the current location */
103
isActive: boolean;
104
/** True if the link matches the current location but not exactly */
105
isPending: boolean;
106
/** True if navigation is currently in progress */
107
isTransitioning: boolean;
108
}
109
```
110
111
**Usage Examples:**
112
113
```tsx
114
import { NavLink } from "react-router-dom";
115
116
// Basic active-aware navigation
117
<NavLink
118
to="/dashboard"
119
className={({ isActive }) => isActive ? "active" : ""}
120
>
121
Dashboard
122
</NavLink>
123
124
// Style function
125
<NavLink
126
to="/profile"
127
style={({ isActive }) => ({
128
color: isActive ? "red" : "blue",
129
textDecoration: isActive ? "underline" : "none"
130
})}
131
>
132
Profile
133
</NavLink>
134
135
// Children function
136
<NavLink to="/notifications">
137
{({ isActive, isPending }) => (
138
<span>
139
Notifications
140
{isPending && " (loading...)"}
141
{isActive && " (current)"}
142
</span>
143
)}
144
</NavLink>
145
146
// Exact matching
147
<NavLink to="/" end>
148
Home
149
</NavLink>
150
```
151
152
### Navigate
153
154
Component for programmatic navigation that triggers on render.
155
156
```typescript { .api }
157
/**
158
* Component that navigates when rendered
159
* @param props - Navigation destination and options
160
* @returns Navigation side effect component
161
*/
162
function Navigate(props: NavigateProps): null;
163
164
interface NavigateProps {
165
/** Navigation destination */
166
to: To;
167
/** Replace current entry instead of pushing */
168
replace?: boolean;
169
/** State to pass with navigation */
170
state?: any;
171
/** Enable relative path resolution */
172
relative?: RelativeRoutingType;
173
}
174
```
175
176
**Usage Example:**
177
178
```tsx
179
import { Navigate } from "react-router-dom";
180
181
function ProtectedRoute({ user, children }) {
182
if (!user) {
183
// Redirect to login if not authenticated
184
return <Navigate to="/login" replace />;
185
}
186
187
return children;
188
}
189
```
190
191
### Form
192
193
Enhanced form component that works with React Router's data loading and actions.
194
195
```typescript { .api }
196
/**
197
* Form component integrated with router actions and data loading
198
* @param props - Form configuration with action handling
199
* @returns Form element with router integration
200
*/
201
function Form(props: FormProps): JSX.Element;
202
203
interface FormProps extends Omit<React.FormHTMLAttributes<HTMLFormElement>, 'action' | 'method'> {
204
/** Form action URL or relative path. Defaults to current route */
205
action?: string;
206
/** HTTP method for form submission */
207
method?: "get" | "post" | "put" | "patch" | "delete";
208
/** Form encoding type */
209
encType?: "application/x-www-form-urlencoded" | "multipart/form-data" | "text/plain";
210
/** Replace current entry instead of pushing */
211
replace?: boolean;
212
/** Enable relative path resolution */
213
relative?: RelativeRoutingType;
214
/** Prevent default scroll reset */
215
preventScrollReset?: boolean;
216
/** Navigate on successful submission */
217
navigate?: boolean;
218
}
219
```
220
221
**Usage Examples:**
222
223
```tsx
224
import { Form } from "react-router-dom";
225
226
// Basic form with action
227
<Form method="post" action="/contact">
228
<input type="text" name="name" required />
229
<input type="email" name="email" required />
230
<textarea name="message" required></textarea>
231
<button type="submit">Send Message</button>
232
</Form>
233
234
// Form with file upload
235
<Form method="post" encType="multipart/form-data">
236
<input type="file" name="document" />
237
<button type="submit">Upload</button>
238
</Form>
239
240
// GET form for search
241
<Form method="get" action="/search">
242
<input type="search" name="q" placeholder="Search..." />
243
<button type="submit">Search</button>
244
</Form>
245
```
246
247
### ScrollRestoration
248
249
Component that manages scroll position during navigation.
250
251
```typescript { .api }
252
/**
253
* Component that manages scroll restoration behavior
254
* @param props - Scroll restoration configuration
255
* @returns Scroll management component
256
*/
257
function ScrollRestoration(props: ScrollRestorationProps): null;
258
259
interface ScrollRestorationProps {
260
/** Function to get scroll restoration key */
261
getKey?: GetScrollRestorationKeyFunction;
262
/** Storage key for scroll positions */
263
storageKey?: string;
264
}
265
266
type GetScrollRestorationKeyFunction = (
267
location: Location,
268
matches: UIMatch[]
269
) => string | null;
270
271
interface UIMatch<Data = unknown, Handle = unknown> {
272
id: string;
273
pathname: string;
274
params: Params;
275
data: Data;
276
handle: Handle;
277
}
278
```
279
280
**Usage Example:**
281
282
```tsx
283
import { ScrollRestoration } from "react-router-dom";
284
285
function Root() {
286
return (
287
<div>
288
{/* Your app content */}
289
<Outlet />
290
291
{/* Restore scroll position on navigation */}
292
<ScrollRestoration />
293
</div>
294
);
295
}
296
```
297
298
## Navigation Patterns
299
300
### Conditional Navigation
301
302
```tsx
303
function ConditionalNavigation({ user, redirectTo }) {
304
if (!user.isAuthenticated) {
305
return <Navigate to={redirectTo} replace />;
306
}
307
308
return <Outlet />;
309
}
310
```
311
312
### Navigation with State
313
314
```tsx
315
// Pass state with navigation
316
<Link
317
to="/details"
318
state={{ from: location.pathname, user: currentUser }}
319
>
320
View Details
321
</Link>
322
323
// Access state in destination component
324
function Details() {
325
const location = useLocation();
326
const { from, user } = location.state || {};
327
328
return (
329
<div>
330
<p>Came from: {from}</p>
331
<p>User: {user?.name}</p>
332
</div>
333
);
334
}
335
```
336
337
### Active Navigation Styling
338
339
```tsx
340
// Multiple active states
341
<nav>
342
<NavLink
343
to="/dashboard"
344
className={({ isActive, isPending }) =>
345
`nav-link ${isActive ? 'active' : ''} ${isPending ? 'pending' : ''}`
346
}
347
>
348
Dashboard
349
</NavLink>
350
</nav>
351
```
352
353
### Form Integration
354
355
```tsx
356
// Form with router action
357
<Form method="post" action="/api/users">
358
<input name="name" type="text" />
359
<input name="email" type="email" />
360
<button type="submit">Create User</button>
361
</Form>
362
363
// Corresponding route
364
<Route
365
path="/users"
366
element={<Users />}
367
action={async ({ request }) => {
368
const formData = await request.formData();
369
const user = {
370
name: formData.get("name"),
371
email: formData.get("email")
372
};
373
return await createUser(user);
374
}}
375
/>
376
```