LoginSignup
1
0

More than 3 years have passed since last update.

GatsbyにTableOfContents(目次)をつける

Last updated at Posted at 2020-05-28

はじめに

本記事は https://tech-blog.yoshikiohashi.dev/posts/start-gatsby-blog-tableofcontent のクロスポスト記事になります。

この記事はGatsbyというヘッドレスCMS技術で構成されています。今回は「エンジニア初心者でもできる」を前提に以下の構成で記事を作成していこうと思います。

内容

前回はタグ一覧と記事一覧のコンポーネントを同時に出すGrapuQLクエリーの応用まで行いました。

今回はブログで欠かせないTableOfContents(目次)の実装方法のご紹介です。全く難しくないのでササッと行きましょう!

クエリー

超簡単です。記事を取得しているクエリーにtableOfContentsを付け足すだけです。エディタで結果を確認してみましょう。

  query PostBySlug($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      id
      html
      fields {
        slug
        tagSlugs
      }
      frontmatter {
        date
        description
        tags
        title
        socialImage
      }
      tableOfContents
    }
  }

このようにHTML形式のデータを取得することができました。あとは表示するだけです。

コンポーネント作成

TOCを表示するコンポーネントつくりです。

ちなみになぜコンポーネントにするのか?理由は単純で

  • 使い回しがしやすい
  • CSSの設定を限定的にできる
  • パーツを好きなところに配置しやすくなる

からです。パーツ1つ1つの依存度を下げていきましょう。

下のようにdangerouslySetInnerHTML={{ __html: tableOfContents }}に先程取得したHTMLデータを流し込みましょう。(CSSの設定はお好みで設定してください)

const Toc = ({ tableOfContents, gridArea }: Props) => (
  <div className={styles.toc} dangerouslySetInnerHTML={{ __html: tableOfContents }} />
);

export default Toc;

まとめ

いかがだったでしょうか?

他にもgatsby-remark-tocなどのライブラリがあるみたいですが、私個人としてはこちらの方がシンプルで簡潔だと考えています。それでは次回の記事で。

1
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
1
0