This repository was archived by the owner on May 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathreact-router-v7.mdc
More file actions
425 lines (345 loc) · 12.5 KB
/
Copy pathreact-router-v7.mdc
File metadata and controls
425 lines (345 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
---
description:
globs:
alwaysApply: true
---
# React Router v7 Framework Mode - Cursor Rules
## 🚨 CRITICAL: Route Type Imports - NEVER MAKE THIS MISTAKE
**THE MOST IMPORTANT RULE: ALWAYS use `./+types/[routeName]` for route type imports.**
```tsx
// ✅ CORRECT - ALWAYS use this pattern:
import type { Route } from "./+types/product-details";
import type { Route } from "./+types/product";
import type { Route } from "./+types/category";
// ❌ NEVER EVER use relative paths like this:
// import type { Route } from "../+types/product-details"; // WRONG!
// import type { Route } from "../../+types/product"; // WRONG!
```
**If you see TypeScript errors about missing `./+types/[routeName]` modules:**
1. **IMMEDIATELY run `typecheck`** to generate the types
2. **Or start the dev server** which will auto-generate types
3. **NEVER try to "fix" it by changing the import path**
## Type Generation & Workflow
- **Run `typecheck` after adding/renaming any routes**
- **Run `typecheck` if you see missing type errors**
- Types are auto-generated by `@react-router/dev` in `./+types/[routeName]` relative to each route file
- **The dev server will also generate types automatically**
---
## Critical Package Guidelines
### ✅ CORRECT Packages:
- `react-router` - Main package for routing components and hooks
- `@react-router/dev` - Development tools and route configuration
- `@react-router/node` - Node.js server adapter
- `@react-router/serve` - Production server
### ❌ NEVER Use:
- `react-router-dom` - Legacy package, use `react-router` instead
- `@remix-run/*` - Old packages, replaced by `@react-router/*`
- React Router v6 patterns - Completely different architecture
## Essential Framework Architecture
### Route Configuration (`app/routes.ts`)
```tsx
import { type RouteConfig, index, route } from "@react-router/dev/routes";
export default [
index("routes/home.tsx"),
route("about", "routes/about.tsx"),
route("products/:id", "routes/product.tsx", [
index("routes/product-overview.tsx"),
route("reviews", "routes/product-reviews.tsx"),
]),
route("categories", "routes/categories-layout.tsx", [
index("routes/categories-list.tsx"),
route(":slug", "routes/category-details.tsx"),
]),
] satisfies RouteConfig;
```
### Route Module Pattern (`app/routes/product.tsx`)
```tsx
import type { Route } from "./+types/product";
// Server data loading
export async function loader({ params }: Route.LoaderArgs) {
return { product: await getProduct(params.id) };
}
// Client data loading (when needed)
export async function clientLoader({ serverLoader }: Route.ClientLoaderArgs) {
// runs on the client and is in charge of calling the loader if one exists via `serverLoader`
const serverData = await serverLoader();
return serverData
}
// Form handling
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData();
await updateProduct(formData);
return redirect(href("/products/:id", { id: params.id }));
}
// Component rendering
export default function Product({ loaderData }: Route.ComponentProps) {
return <div>{loaderData.product.name}</div>;
}
```
### Layout/Parent Routes with Outlet
**For layout routes that have child routes, ALWAYS use `<Outlet />` to render child routes:**
```tsx
import type { Route } from "./+types/categories-layout";
import { Outlet } from "react-router";
export default function CategoriesLayout(props: Route.ComponentProps) {
return (
<div className="layout">
<nav>
{/* Sidebar or navigation */}
</nav>
<main>
<Outlet /> {/* ✅ This renders the matching child route */}
</main>
</div>
);
}
// ❌ Never use `children` from the component props, it doesn't exist
// export default function CategoriesLayout({ children }: Route.ComponentProps) {
## Automatic Type Safety & Generated Types
**React Router v7 automatically generates types for every route.** These provide complete type safety for loaders, actions, components, and URL generation.
### ✅ ALWAYS Use Generated Types:
Types are autogenerated and should be imported as `./+types/[routeFileName]`. **If you're getting a type error, run `npm run typecheck` first.**
The filename for the autogenerated types is always a relative import of `./+types/[routeFileName]`:
```tsx
// routes.ts
route("products/:id", "routes/product-details.tsx")
// routes/product-details.tsx
// ✅ CORRECT: Import generated types for each route
import type { Route } from "./+types/product-details";
export async function loader({ params }: Route.LoaderArgs) {
// params.id is automatically typed based on your route pattern
return { product: await getProduct(params.id) };
}
export default function ProductDetails({ loaderData }: Route.ComponentProps) {
// loaderData.product is automatically typed from your loader return
return <div>{loaderData.product.name}</div>;
}
```
### ✅ Type-Safe URL Generation with href():
```tsx
import { Link, href } from "react-router";
// Static routes
<Link to={href("/products/new")}>New Product</Link>
// Dynamic routes with parameters - AUTOMATIC TYPE SAFETY
<Link to={href("/products/:id", { id: product.id })}>View Product</Link>
<Link to={href("/products/:id/edit", { id: product.id })}>Edit Product</Link>
// Works with redirects too
return redirect(href("/products/:id", { id: newProduct.id }));
```
### ❌ NEVER Create Custom Route Types:
```tsx
// ❌ DON'T create custom type files for routes
export namespace Route {
export interface LoaderArgs { /* ❌ */ }
export interface ComponentProps { /* ❌ */ }
}
// ❌ DON'T manually construct URLs - no type safety
<Link to={`/products/${product.id}`}>Product</Link> // ❌
<Link to="/products/" + product.id">Product</Link> // ❌
```
### Type Generation Setup:
- **Location**: Types generated in `./+types/[routeName]` relative to each route file
- **Auto-generated**: Created by `@react-router/dev` when you run dev server or `npm run typecheck`
- **Comprehensive**: Covers `LoaderArgs`, `ActionArgs`, `ComponentProps`, `ErrorBoundaryProps`
- **TypeScript Config**: Add `.react-router/types/**/*` to `include` in `tsconfig.json`
## Critical Imports & Patterns
### ✅ Correct Imports:
```tsx
import { Link, Form, useLoaderData, useFetcher, Outlet } from "react-router";
import { type RouteConfig, index, route } from "@react-router/dev/routes";
import { data, redirect, href } from "react-router";
```
## Data Loading & Actions
### Server vs Client Data Loading:
```tsx
// Server-side rendering and pre-rendering
export async function loader({ params }: Route.LoaderArgs) {
return { product: await serverDatabase.getProduct(params.id) };
}
// Client-side navigation and SPA mode
export async function clientLoader({ params }: Route.ClientLoaderArgs) {
return { product: await fetch(`/api/products/${params.id}`).then(r => r.json()) };
}
// Use both together - server for SSR, client for navigation
clientLoader.hydrate = true; // Force client loader during hydration
```
### Form Handling & Actions:
```tsx
// Server action
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData();
const result = await updateProduct(formData);
return redirect(href("/products"));
}
// Client action (takes priority if both exist)
export async function clientAction({ request }: Route.ClientActionArgs) {
const formData = await request.formData();
await apiClient.updateProduct(formData);
return { success: true };
}
// In component
<Form method="post">
<input name="name" placeholder="Product name" />
<input name="price" type="number" placeholder="Price" />
<button type="submit">Save Product</button>
</Form>
```
## Navigation & Links
### Basic Navigation:
```tsx
import { Link, NavLink } from "react-router";
// Simple links
<Link to="/products">Products</Link>
// Active state styling
<NavLink to="/dashboard" className={({ isActive }) =>
isActive ? "active" : ""
}>
Dashboard
</NavLink>
// Programmatic navigation
const navigate = useNavigate();
navigate("/products");
```
### Advanced Navigation with Fetchers:
```tsx
import { useFetcher } from "react-router";
function AddToCartButton({ productId }: { productId: string }) {
const fetcher = useFetcher();
return (
<fetcher.Form method="post" action="/api/cart">
<input type="hidden" name="productId" value={productId} />
<button type="submit">
{fetcher.state === "submitting" ? "Adding..." : "Add to Cart"}
</button>
</fetcher.Form>
);
}
```
## File Organization & Naming
### ✅ Flexible File Naming:
React Router v7 uses **explicit route configuration** in `app/routes.ts`. You are NOT constrained by old file-based routing conventions.
```tsx
// ✅ Use descriptive, clear file names
export default [
route("products", "routes/products-layout.tsx", [
index("routes/products-list.tsx"),
route(":id", "routes/product-details.tsx"),
route(":id/edit", "routes/product-edit.tsx"),
]),
] satisfies RouteConfig;
```
### File Naming Best Practices:
- Use **descriptive names** that clearly indicate purpose
- Use **kebab-case** for consistency (`product-details.tsx`)
- Organize by **feature** rather than file naming conventions
- The **route configuration** is the source of truth, not file names
## Error Handling & Boundaries
### Route Error Boundaries:
Only setup `ErrorBoundary`s for routes if the users explicitly asks. All errors bubble up to the `ErrorBoundary` in `root.tsx` by default.
```tsx
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
if (isRouteErrorResponse(error)) {
return (
<div>
<h1>{error.status} {error.statusText}</h1>
<p>{error.data}</p>
</div>
);
}
return (
<div>
<h1>Oops!</h1>
<p>{error.message}</p>
</div>
);
}
```
### Throwing Errors from Loaders/Actions:
```tsx
export async function loader({ params }: Route.LoaderArgs) {
const product = await db.getProduct(params.id);
if (!product) {
throw data("Product Not Found", { status: 404 });
}
return { product };
}
```
## Advanced Patterns
### Pending UI & Optimistic Updates:
```tsx
import { useNavigation, useFetcher } from "react-router";
// Global pending state
function GlobalSpinner() {
const navigation = useNavigation();
return navigation.state === "loading" ? <Spinner /> : null;
}
// Optimistic UI with fetchers
function CartItem({ item }) {
const fetcher = useFetcher();
const quantity = fetcher.formData
? parseInt(fetcher.formData.get("quantity"))
: item.quantity;
return (
<fetcher.Form method="post">
<input
type="number"
name="quantity"
value={quantity}
onChange={(e) => fetcher.submit(e.currentTarget.form)}
/>
{item.product.name}
</fetcher.Form>
);
}
```
### Progressive Enhancement:
```tsx
// Works without JavaScript, enhanced with JavaScript
export default function ProductSearchForm() {
return (
<Form method="get" action="/products">
<input type="search" name="q" placeholder="Search products..." />
<button type="submit">Search</button>
</Form>
);
}
```
## Anti-Patterns to Avoid
### ❌ React Router v6 Patterns:
```tsx
// DON'T use component routing
<Routes>
<Route path="/" element={<Home />} />
</Routes>
```
### ❌ Manual Data Fetching:
```tsx
// DON'T fetch in components
function Product() {
const [data, setData] = useState(null);
useEffect(() => { fetch('/api/products') }, []);
// Use loader instead!
}
```
### ❌ Manual Form Handling:
```tsx
// DON'T handle forms manually
const handleSubmit = (e) => {
e.preventDefault();
fetch('/api/products', { method: 'POST' });
};
// Use Form component and action instead!
```
## Essential Type Safety Rules
1. **ALWAYS** import from `"./+types/[routeName]"` - never use relative paths like `"../+types/[routeName]"`
2. **RUN `npm run typecheck`** when you see missing type errors - never try to "fix" the import path
3. **ALWAYS** use `href()` for dynamic URLs - never manually construct route strings
4. **LET TypeScript infer** loader/action return types - don't over-type returns
5. **USE Route.ComponentProps** for your route components - automatic loaderData typing
6. **ADD** `.react-router/types/**/*` to your `tsconfig.json` include array
## AI Assistant Guidelines
When working with React Router v7:
- **If you see missing `./+types/[routeName]` imports, ALWAYS suggest running `npm run typecheck` first**
- **NEVER suggest changing `./+types/[routeName]` to `../+types/[routeName]` or any other relative path**
- **After creating new routes, remind the user to run `npm run typecheck`**
- **Assume types need to be generated if they're missing, don't assume the dev server is running**