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.
- 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;
- 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;