-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path105-nextjs-routes.mdc
71 lines (40 loc) · 2.29 KB
/
105-nextjs-routes.mdc
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
---
description: EXPLAIN how to create and use routing file in NextJS
globs: *.tsx
---
## Context
* NextJS is a framework that handle route for us.
* Here is exactly how to create and handle route in our application.
* We can only handle route in `app` directory
## `page.tsx`
The template for page is located in [npag.code-snippets](mdc:.vscode/npag.code-snippets) and define a page. You can also use [npagl.code-snippets](mdc:.vscode/npagl.code-snippets) for having a default layout. Here is how page work :
* `/app/users/page.tsx` will route in `/users`
The params is ASYNC and you must use [next.ts](mdc:src/types/next.ts) to use the params with PageParams.
Exemple :
```tsx
import type { PageParams } from "@/types/next";
// You always need to use PageParams
export default async function RoutePage(props: PageParams<{ userId: string }>) {
// You need to await searchParams
const searchParams = await props.searchParams;
const page = searchParams.page;
// You need to await params
const params = await props.params;
const userId = params.userId;
return // ...
}
```
## `layout.tsx`
The template for the layout is located in [nlay.code-snippets](mdc:.vscode/nlay.code-snippets) and define the layout that will be applied to every child of a route.
* `/app/users/layout.tsx` will take a children and every route will have the layout applied, exemple :
* `/users/1`
* `/users`
* `/users/dashboard/test`
The params is ASYNC and you must use [next.ts](mdc:src/types/next.ts) to use the params with LayoutParams.
## `error.tsx`
The template can be found in [nerr.code-snippets](mdc:.vscode/nerr.code-snippets) and define the Error page. When a child routes get an error, the `error` will be displayed. It's the nearest error in the tree that will be displayed. It's a good practice to always add an error.
* `/app/users/error.tsx` will show an error for every route that didn't have a nearest error, children of `/users`
## `loading.tsx`
The template can be found in [nloa.code-snippets](mdc:.vscode/nloa.code-snippets) and define the Loading page.
When a child is a [server-components.mdc](mdc:.cursor/rules/server-components.mdc) and wait, the `loading.tsx` page will be displayed.
* `/app/users/loading.tsx` will show a loader for every route that didn't have a nearest loading, children of `/users`