Juxt
免費訂閱
文章 · 收錄於 2024.02
MGN-BLOG-PREVNEXT
索引 · 部落格

PrevNext Blog Component for NextJS Using ContentLayer

2 分鐘閱讀

Using ContentLayer, it's easy to create a Prev & Next component if you want to encourage users to read one blog article and then the order. All it takes are two simple step.

  1. Create related posts logic on blog single page

You should already have blog single page setup in the file like /blog/[slug].tsx. In addition to it you will need to create an index of posts, assuming you want to build a chronological order. And then retrieve the next and and previous posts base on the current post's index. if there is a post following the current one and assigns it to nextPost, and likewise for the previous post, assigning it to prevPost.

const currentIndex = fileredWorks.findIndex(
  (post) => post.slug === params?.slug,
);

const nextPost =
  currentIndex < fileredWorks.length - 1
    ? fileredWorks[currentIndex + 1]
    : null;

const prevPost = currentIndex > 0 ? fileredWorks[currentIndex - 1] : null;
  1. Create a PrevNext Component

Then now you can create a new component called "PrevNext". It will accept the created props prevPost and nextPosts. For example, I'm using

import { Box, LinkBox, Text } from "@chakra-ui/react";
import { Work } from "contentlayer/generated";
import React from "react";
import NextLink from "@/components/NextLink";

const NextPrev = ({
prevPost,
nextPost,
}: {
nextPost: Work;
prevPost: Work;
}) => {

return (

<Box my="16">
{prevPost && (
	<Link href={`/work/${prevPost.slug}`}>
		<button>Previous: {prevPost.title}</button>
	</Link>
)}

{nextPost && (
<Box border="1px solid" borderColor="border" px="8" py="6" rounded="md">
	<NextLink href={`/work/${nextPost.slug}`}>
		<Text variant="small" color="secondarytext" my="0">Read next →</Text>
		<Text fontSize="lg" my="0">{nextPost.title}</Text>
	</NextLink>
</Box>
)}

</Box>
);
};

export default NextPrev;
標籤Nextjs
索引 · 相關文章

延伸閱讀

文章 · 01
預覽圖
nextjs
Migrating from Gatsby to Next.js 14

This website has entered v3 of its iteration! v2 was created using Gatsby and integrated with my previous design resources `dojo.today`. Entering v3, I'm migrating the website from Gatsby to Next.js 14! Things that I'm considering during the revamp: For me there are two key pillar of content that require to migrate from this website 1. Blog articles on juxtdesign.cc that previously saved as Markd

部落格
文章 · 02
預覽圖
nextjs
NextJS Modal with shadcn for Intercepting and Parallel Routes

Intercepting Routes was a new feature firstly released in NextJS 13. Currently NextJS file-based route system is like a sitemap, there are no specific order on how the route is read or triggered. In NextJS documentation, it also wrote: Note that the `(..)` convention is based on _route segments_, not the file-system. Intercepting route thinks differently by thinking how would a user enters a route

部落格