From a9550fb4350ca64540bd13e4e0ffc9e56db8d02f Mon Sep 17 00:00:00 2001 From: Hugo ChunHo Lin Date: Thu, 12 Sep 2024 14:02:52 +0800 Subject: [PATCH] feat(blog): implement pagination for blog posts (#241) --- apps/web/src/app/blog/page.tsx | 101 +++++++++++++++++++++------------ 1 file changed, 64 insertions(+), 37 deletions(-) diff --git a/apps/web/src/app/blog/page.tsx b/apps/web/src/app/blog/page.tsx index edebd5d0..010b4436 100644 --- a/apps/web/src/app/blog/page.tsx +++ b/apps/web/src/app/blog/page.tsx @@ -12,16 +12,36 @@ export const metadata = { let blogTags: string[] = ['All']; -export default function BlogPage({ searchParams }: { searchParams: { tag?: string } }) { +const POSTS_PER_PAGE = 4; + +export default function BlogPage({ searchParams }: { searchParams: { tag?: string; page?: string } }) { let allBlogs = getBlogPosts(); blogTags = ['All', ...Array.from(new Set(allBlogs.map(post => post.metadata.category ?? '')))]; const selectedTag = searchParams.tag || 'All'; + const currentPage = parseInt(searchParams.page || '1', 10); // Filter blogs based on the selected tag const filteredBlogs = selectedTag === 'All' ? allBlogs : allBlogs.filter(post => post.metadata.category === selectedTag); + // Sort blogs by date + const sortedBlogs = filteredBlogs.sort((a, b) => { + if (new Date(a.metadata.publishedAt) > new Date(b.metadata.publishedAt)) { + return -1; + } + return 1; + }); + + // Calculate total pages + const totalPages = Math.ceil(sortedBlogs.length / POSTS_PER_PAGE); + + // Get blogs for current page + const paginatedBlogs = sortedBlogs.slice( + (currentPage - 1) * POSTS_PER_PAGE, + currentPage * POSTS_PER_PAGE + ); + return (
@@ -30,44 +50,51 @@ export default function BlogPage({ searchParams }: { searchParams: { tag?: strin
    - {filteredBlogs - .sort((a, b) => { - if (new Date(a.metadata.publishedAt) > new Date(b.metadata.publishedAt)) { - return -1; - } - return 1; - }) - .map((post, index) => ( -
  • - -
    - {post.metadata.alt -
    -
    -
    -

    {post.metadata.category}

    - - -
    -

    {post.metadata.title}

    -

    {post.metadata.summary}

    + {paginatedBlogs.map((post, index) => ( +
  • + +
    + {post.metadata.alt +
    +
    +
    +

    {post.metadata.category}

    + +
    - -
  • - ))} +

    {post.metadata.title}

    +

    {post.metadata.summary}

    + + + + ))}
+
+ {Array.from({ length: totalPages }, (_, i) => i + 1).map((pageNum) => ( + + {pageNum} + + ))} +
);