PrevNext Blog Component for NextJS Using ContentLayer

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 = ({
}: {
nextPost: Work;
prevPost: Work;
}) => {
return (
<Box my="16">
{prevPost && (
	<Link href={`/work/${prevPost.slug}`}>
		<button>Previous: {prevPost.title}</button>
{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>
export default NextPrev;
Last Updated
February 25, 2024

Related posts

    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 ``. Entering v3, I'm migrating the website from Gatsby to Next.js 1