Written by
JJoo
on
on
Next.js에서의 동적 라우팅
Next.js의 routing
Next.js에서는 page파일안에 생성되는 파일들의 구조와 파일명들로 자동으로 route가 생성된다.
ex)
├── pages
│ ├── index.tsx
│ ├── faq.tsx
│ └── post.tsx
│ ├── post1.tsx
│ ├── post2.tsx
│ └── post3.tsx
- /
- /faq
- /post/post1
- /post/post2
- /post/post3
그렇다면 Next.js에서 동적 라우팅을 하려면?
폴더명을 대괄호로 감싸서 지정해주면 된다.
ex) [id]
, [postNum]
…
대괄호로 감싼 폴더명은 route.query
에 저장이 된다.
ex)
├── pages
│ ├── index.tsx
│ ├── faq.tsx
│ └── post.tsx
│ └── [id]
│ ├── post1.tsx
│ ├── post2.tsx
│ └── post3.tsx
- /
- /faq
- /post/3/post1
- /post/3/post2
- /post/3/post3
route.query
에 저장된 내용 확인해보면 아래와 같다.
console.log(route.query);
// { id:3 }
그렇다면 동적 라우팅을 다중으로 적용하고 싶으면?
만약에 학교별로 게시글을 보여주고 싶은 경우라고 가정해보자.
학교마다 고유의 id가 있고 그 id별로 게시글들을 보여주고 싶다.
ex)
├── pages
│ ├── index.tsx
│ ├── faq.tsx
│ └── ㄴschool.tsx
│ └── [schoolId]
│ └── post.tsx
│ └── [postId]
│ ├── post1.tsx
│ ├── post2.tsx
│ └── post3.tsx
- /
- /faq
- /school/1/post/3/post1
- /school/1/post/3/post2
- /school/1/post/3/post3
대략 1번 학교의 3번 학생이 쓴 글은 이런 경로로 보여질 것이다.
이때 route.query
에 저장된 내용 확인해보면 아래와 같다.
console.log(route.query);
// { schoolId:1, postId:3}
raect redux의 store는 새로고침하면 store가 비워지는 데 이럴 때 route.query
에 담긴 값들을 활용할 수 도 있다.
Discussion and feedback