0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[microCMS] ブログ記事で目次を Next.js で作ったフロントに追加する

0
Last updated at Posted at 2026-11-18

やりたいこと

ブログ記事の目次を作りたい

  • 記事内の見出しタグを自動で抽出してページ内リンクを加える
  • リード文→目次→見出し、本文 の順で表示

参考にした記事

microCMSで目次を作成する
https://blog.microcms.io/create-table-of-contents/

コード例

オリジナルのテンプレートにコードを追加する形で実装しています。
ほぼ、参考にした記事と同じ内容です。

/components/TableOfContents/index.tsx で目次のマークアップを行います。
ここに渡す目次の配列やCSSクラスは記事ページで組み立てています。

/components/TableOfContents/index.tsx
import { TocItem } from '@/libs/utils';

type Props = {
  toc: TocItem[];
  className?: string;
};

export const TableOfContents = ({ toc, className }: Props) => {
  return (
    <div className={className}>
      <p>目次</p>
      <ul>
        {toc.map((data) => (
          <li key={data.id}>
            <a href={`#${data.id}`}>{data.text}</a>
          </li>
        ))}
      </ul>
    </div>
  );
};

ただし、このコードの場合、h2やh3でリストの階層化ができません。
見た目(CSS)でインデントをつけることはできるので、そのあたりは先の参考記事を参考に <li> へCSSクラスを付与するなどしてください。

/components/Article/index.tsx 記事の本文を表示しているテンプレートで本文から目次の抽出を行い、CSSクラスとともに/components/TableOfContents/index.tsxへ渡しています。

components/Article/index.tsx
import { formatRichText, renderToc } from '@/libs/utils'; //renderTocを追加
import { type Article } from '@/libs/microcms';
import PublishedDate from '../Date';
import styles from './index.module.css';
import CategoryList from '../CategoryList';
import TagList from '../TagList';
import ArticleContent from '../ArticleContent';
import ShareButton from '../ShareButton';
import { microCMSRichEditorHandler, responsiveImageTransformer } from 'microcms-rich-editor-handler';
import { TableOfContents } from '../TableOfContents'; //TableOfContentsを追加

type Props = {
  data: Article;
};

export default async function Article({ data }: Props) {
  const toc = renderToc(data.content || '');

(略)

  return (
    <main className={styles.main}>
      <h1 className={styles.title}>{data.title}</h1>
(略)

      {/* リード文 description を表示 */}
      {data.description && (
        <p className={styles.description}>{data.description}</p>
      )}

      {/* 目次を表示 */}
      <TableOfContents toc={toc} className={styles.toc} />

      {/* 本文 content を表示 */}
      <ArticleContent
        html={processedContent}
        className={styles.content}
      />

(略)
    </main>
  );
}

CSSは適宜調整してください。

現場からは以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?