Dev/JS Family, HTML, CSS
Nextjs 공식문서로 공부하기 - 동적 라우팅
youngst
2023. 3. 5. 01:45
Dynamic Routes
Next.js는 외부 데이터에 따라 동적으로 라우팅 주소를 사용할 수 있는 '동적 라우팅(Dynamic Routing)'을 지원한다. 가장 흔한 예로는 블로그 포스트의 번호에 따라 /post/1
, /post/2
이런식으로 나누는 것이다.
구현 방법은 간단하게 [
과 ]
로 파일명을 감싸면 된다. ./posts/[id].js
이런 식이다. 컴포넌트 이름은 그대로 사용하면 된다. 다음과 같은 형태로 사용할 수 있다.
import Layout from '../../components/layout';
export default function Post() {
return <Layout>...</Layout>;
}
export async function getStaticPaths() {
// Returns an array that looks like this:
// [
// {
// params: {
// id: 'ssg-ssr'
// }
// },
// {
// params: {
// id: 'pre-rendering'
// }
// }
// ]
const paths = getAllPostIds();
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params }) {
// Fetch necessary data for the blog post using params.id
}
이전에 다뤘던 getStaticProps
에 더해 getStaticPaths
라는 새로운 함수가 추가되었다.
getStaticPaths
getStaticPaths
는 paths
와 fallback
을 포함하는 객체를 리턴해야한다. 이때 paths
는 params
라는 요소를 포함하는 객체이다. params
는 동적 요소로 쓰일 변수의 이름(여기선 id
)을 포함해야한다!
이를 모두 포함해 구현하면 아래의 예제가 된다.
import Layout from "../../components/layout";
import { getPostData } from "../../lib/posts";
export default function Post({ postData }) {
return (
<Layout>
{postData.title}
<br />
{postData.id}
<br />
{postData.date}
</Layout>
);
}
export async function getStaticPaths() {
const paths = getAllPostIds();
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params }) {
// Fetch necessary data for the blog post using params.id
const postData = getPostData(params.id);
return {
props: {
postData,
},
};
}
위 코드에서 getStaticProps
는 URL에서 params
를 받는다!! 리액트 라우터의 params
와 비슷하다. 공식문서의 예제에서는 파일명을 id로 이용했지만, 일반적인 블로그에서는 API로 받은 id 값을 넣어주면 된다.