1. Next.js 동적 라우팅
Next.js에서는 폴더 구조를 이용해 URL을 만들 수 있다.
예를 들어 게시물 상세 페이지를 다음과 같이 만들 수 있다.
app/
└── posts/
├── page.tsx
└── [id]/
└── page.tsx
이렇게 [id] 형태로 폴더를 만들면 id가 동적으로 변하는 URL 값이 된다.
따라서 다음과 같은 URL을 사용할 수 있다.
/posts/1
/posts/2
/posts/3
각 URL에서 1, 2, 3이 id에 해당한다.
/posts/1
↑
id
2. useParams()로 URL의 값 가져오기
동적 라우팅에서 URL에 들어있는 값을 가져올 때 useParams()를 사용할 수 있다.
'use client';
import { useParams } from "next/navigation";
export default function Detail() {
const { id } = useParams();
return (
<div>
게시물 번호 : {id}
</div>
);
}
/posts/10으로 접속하면 id에는 "10"이 들어오게 된다.
3. URL의 id를 이용해 상세 API 호출하기
useParams()로 가져온 id를 이용하면 특정 게시물의 API를 호출할 수 있다.
"use client";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
interface PostDto {
id: number;
title: string;
content: string;
createDate: string;
modifyDate: string;
}
export default function Detail() {
const { id } = useParams();
const [post, setPost] = useState<PostDto | null>(null);
useEffect(() => {
fetch(`http://localhost:8080/api/v1/posts/${id}`)
.then((res) => res.json())
.then((data) => {
setPost(data);
});
}, [id]);
if (post === null) {
return <div>로딩중...</div>;
}
return (
<div>
<h1>상세 페이지</h1>
<div>번호 : {post.id}</div>
<div>제목 : {post.title}</div>
<div>내용 : {post.content}</div>
</div>
);
}
4. 로딩 상태 처리하기
API 요청은 바로 완료되지 않을 수 있기 때문에 데이터를 받기 전까지 보여줄 화면이 필요하다.
if (post === null) {
return <div>로딩중...</div>;
}
처음에는 post가 null이다.
if (post === null) {
return <div>로딩중...</div>;
}
API 응답을 받으면 setPost(data)를 통해 실제 게시물 데이터가 저장된다.
따라서 다음과 같이 동작한다.
처음 화면
↓
post === null
↓
"로딩중..." 출력
↓
API 응답
↓
setPost(data)
↓
화면 다시 렌더링
↓
게시물 정보 출력
이렇게 하면 API 응답을 기다리는 동안에도 사용자에게 현재 상태를 알려줄 수 있다.
'Frontend > Next.js' 카테고리의 다른 글
| Next.js에서 REST API 호출하기 | fetch, async/await, useEffect (0) | 2026.08.19 |
|---|---|
| Next.js 페이지와 Layout 정리 (0) | 2026.08.19 |
댓글