Web Devlopment/Next-Blog Project
#10. Read Blog Posts (home)
키모형
2025. 4. 5. 18:44
반응형
db collection에서 posts 데이터를 최신 등록 순으로 조회해서 표시
PostCard 를 컴포넌트로 분리해서 구현
/src/app/page.jsx
import PostCard from "@/components/PostCard";
import { getCollection } from "@/lib/db";
export default async function Home() {
const postsCollection = await getCollection("posts");
const posts = await postsCollection?.find().sort({ $natural: -1 }).toArray();
if(posts){
return (
<div className="grid grid-cols-2 gap-6">
{
posts.map((post) => (
<div key={post._id}>
<PostCard post={post} />
</div>
))
}
</div>
);
} else {
return <p>Failed to fetch the data from database.</p>
}
}
/src/components/PostCard.jsx
import Link from "next/link";
export default function PostCard({ post }) {
return (
<div className="border border-slate-400 border-dashed p-4 rounded-md h-full">
<p className="text-slate-600 text-sm">
{post._id.getTimestamp().toLocaleString("ko-KR")}
</p>
<Link href="" className="block text-xl font-semibold mb-4">
{post.title}
</Link>
<p className="text-sm">{post.content}</p>
</div>
);
}
반응형