From 356a1af2e03932ad183dc161b1e529041d20fddb Mon Sep 17 00:00:00 2001 From: Serhii Shramko Date: Sat, 13 Jul 2024 18:25:25 -0400 Subject: [PATCH] feat: add next & prev pages functionality --- pages/blog/[slug].tsx | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/pages/blog/[slug].tsx b/pages/blog/[slug].tsx index a0a1ee0..ab4d692 100644 --- a/pages/blog/[slug].tsx +++ b/pages/blog/[slug].tsx @@ -5,7 +5,7 @@ import { MDXRemote, MDXRemoteSerializeResult } from 'next-mdx-remote'; import { GetStaticPathsResult, GetStaticPropsContext, GetStaticPropsResult } from 'next'; import { ParsedUrlQuery } from 'querystring'; -import { getPostBySlug, getPostSlugs } from '@/lib/posts/api'; +import { getPostBySlug, getPosts, getPostSlugs } from '@/lib/posts/api'; import { compileMDX } from '@/lib/scripts/compiler'; import { Post } from '@/lib/types'; @@ -14,9 +14,12 @@ import { ViewCounter } from '@/components/view-counter/view-counter'; import { FacebookShare, LinkedInShare, TelegramShare, TwitterShare, } from '@/components/share-button'; +import { sortByBirthtime } from '@/lib/posts/utils'; type ArticlePageProps = Pick & { content: MDXRemoteSerializeResult; + prevPostSlug: string, + nextPostSlug: string, }; function ArticlePage(props: ArticlePageProps) { @@ -33,6 +36,8 @@ function ArticlePage(props: ArticlePageProps) { categories = [], keywords, }, + nextPostSlug, + prevPostSlug, } = props; const formattedDate = new Date(createDate).toLocaleDateString('en-us', { @@ -158,6 +163,30 @@ function ArticlePage(props: ArticlePageProps) { +
    + {prevPostSlug && ( +
  • + + 👈 Previous article + +
  • + )} + + {nextPostSlug && ( +
  • + + Next article 👉 + +
  • + )} +
+

Share it:

    @@ -192,11 +221,17 @@ export async function getStaticProps({ > { const { data, content } = await getPostBySlug(params?.slug); const html = await compileMDX(content); + const posts = await getPosts(); + const currentPostIndex = posts.sort(sortByBirthtime).findIndex((post) => post.data.slug === data.slug); + const prevPost = posts[currentPostIndex + 1] || null; + const nextPost = posts[currentPostIndex - 1] || null; return { props: { data, content: html, + prevPostSlug: prevPost?.data.slug || '', + nextPostSlug: nextPost?.data.slug || '', }, }; }