📖

Next.js + microCMSで前後の記事へ遷移できるPrev/Nextナビゲーションを作る方法

この記事の目的

Next.js + microCMS で前後の記事へ遷移できる Prev/Next ナビゲーションを作る方法を学ぶ

完成イメージ

・前後に記事がある場合のみ表示

・更新順で並んでいる記事の中から前後を判定

記事の並び順について

今回の実装では、microCMS から記事を取得するときに orders: "-publishedAt" を指定します。
これは 公開日の新しい順(降順) に並べる設定です。

表示順 記事 index
最新の記事 A 0
1 つ前の記事 B 1
2 つ前の記事 C 2

したがって

・前の記事 = currentIndex + 1

・次の記事 = currentIndex - 1

現在の記事位置を取得するロジック

findIndex() を利用して、配列の中で現在表示している記事が何番目かを取得します

const currentIndex = contents.findIndex((a) => a.id === currentId);

findIndex() は、配列の中から条件に一致する要素の index を返す関数です。

実装コード

import Link from "next/link";
import { client } from "@/libs/microcms";
import { HiArrowNarrowLeft, HiArrowNarrowRight } from "react-icons/hi";

type ArticleProps = {
  id: string;
  title: string;
  publishedAt?: string;
};

type ArticleNavigationProps = {
  currentId: string;
};

export default async function ArticleNavigation({
  currentId,
}: ArticleNavigationProps) {
  const { contents } = await client.get<{ contents: ArticleProps[] }>({
    endpoint: "",
    queries: {
      fields: "id,title,publishedAt",
      limit: 100,
      orders: "-publishedAt",
    },
  });

  const currentIndex = contents.findIndex((a) => a.id === currentId);

  const prev = contents[currentIndex + 1];
  const next = contents[currentIndex - 1];

  return (
    <div className="flex w-full justify-between">
      {prev ? (
        <Link href={`/articles/${prev.id}`}>
          <div className="flex flex-col items-center">
            <HiArrowNarrowLeft className="text-4xl sm:text-6xl" />
            <p className="text-xs sm:text-sm">前の記事へ</p>
          </div>
        </Link>
      ) : (
        <div />
      )}

      {next ? (
        <Link href={`/articles/${next.id}`}>
          <div className="flex flex-col items-center">
            <HiArrowNarrowRight className="text-4xl sm:text-6xl" />
            <p className="text-xs sm:text-sm">次の記事へ</p>
          </div>
        </Link>
      ) : (
        <div />
      )}
    </div>
  );
}

解説

findIndex

特定の条件に一致する要素が配列の何番目にいるかを返す関数。
今回の場合は id が一致する記事の位置を取得しています。

orders: "-publishedAt"

公開日が 新しい順 に並べる設定。
先頭が最新になるようにして、index で前後関係を判定します

prev と next

const prev = contents[currentIndex + 1]; // 1つ前の記事
const next = contents[currentIndex - 1]; // 1つ後の記事

記事数が多い場合は limit の調整やページング検討が必要です。

最後に

この記事では、Next.js + microCMS を使って、記事詳細ページから「前の記事」「次の記事」へ遷移できるナビゲーションの作り方を紹介しました。

orders で並び順を指定して index を活用する

findIndex で現在の記事位置を取得

index をもとに prev, next を取得

ブログ開発やポートフォリオ制作の際にご参考になると幸いです。

📌 ご意見・ご感想などあればぜひコメントお願いします。

GitHubで編集を提案
デザインエンジニアリング テックブログ

Discussion