Next.js 13+ 환경에서 뉴스 데이터를 효율적으로 구조화하고 표시하는 방법을 알아보겠습니다.
먼저 types/news.ts
파일에서 뉴스 기사의 타입을 정의합니다:
interface NewsArticle {
title: string;
source: string;
publishedAt: string;
content: string[];
}
data/newsData.ts
파일에서 뉴스 데이터를 구조화합니다:
export const newsData: NewsArticle = {
title: "'승무원 출신' 류이서·성해은·김지영, 여객기 참사에 깊은 슬픔 "얼마나 무서웠을까" [종합]",
source: "스타뉴스",
publishedAt: "2024-12-31 10:14",
content: [
"성해은도 이날 여객기 참사 희생자들에 대한 애도를 표했다. 그는 "참담하다"며 "깊은 애도의 마음을 표한다. 삼가 고인의 명복을 빈다"고 밝혔다.",
"성해은은 2020년 방송된 티빙 오리지널 '환승연애 2'에 출연해 이름을 알렸다. 대한항공 승무원 출신인 그는 현재는 퇴사 후 인플루언서로 활동하고 있다.",
// ... 추가 content 배열 항목들
]
};
components/NewsArticle.tsx
파일에서 뉴스 기사를 표시할 컴포넌트를 생성합니다:
import { NewsArticle } from '../types/news';
interface NewsArticleProps {
article: NewsArticle;
}
export default function NewsArticle({ article }: NewsArticleProps) {
return (
<article className="max-w-4xl mx-auto p-4 space-y-4">
<header className="space-y-2">
<h1 className="text-2xl font-bold">
{article.title}
</h1>
<div className="text-sm text-gray-600">
{article.source} 원문 기사전송 <time>{article.publishedAt}</time>
</div>
</header>
<div className="space-y-4">
{article.content.map((paragraph, index) => (
<p key={index} className="whitespace-pre-wrap">
{paragraph}
</p>
))}
</div>
</article>
);
}
pages/news/[id].tsx
또는 app/news/[id]/page.tsx
파일에서 컴포넌트를 사용합니다:
import { NewsArticle } from '../../components/NewsArticle';
import { newsData } from '../../data/newsData';
export default function NewsPage() {
return <NewsArticle article={newsData} />;
}
타입 안전성
스타일링
접근성
async function getNewsArticle(id: string): Promise<NewsArticle> {
const response = await fetch(`/api/news/${id}`);
return response.json();
}
try {
const article = await getNewsArticle(id);
// ... render article
} catch (error) {
return <ErrorComponent message="기사를 불러오는데 실패했습니다." />;
}
if (isLoading) {
return <LoadingSpinner />;
}
이러한 구조를 사용하면 뉴스 데이터를 체계적으로 관리하고 표시할 수 있으며, 필요에 따라 기능을 확장하기도 용이합니다.