okaryo.log

Displaying a Table of Contents on a Gatsby Blog Post Page | okaryo.log

Displaying a Table of Contents on a Gatsby Blog Post Page

    #Gatsby

Introduction

As the length of a blog post increases, it becomes difficult to grasp the overall structure just by reading from the top. Additionally, I wanted to increase the read-through rate of the article by allowing users who land on the article page to quickly understand its content.

For these reasons, I decided to create a table of contents for this blog. Since this blog is built with Gatsby, I’ll introduce how to create a table of contents in Gatsby.

How to Create a Table of Contents

The table of contents is often referred to as “TOC,” an acronym for “Table Of Contents.” I initially thought I would need to introduce a library for generating the TOC, but it was easily achieved in Gatsby without doing so.

There’s a field named tableOfContents in the MarkdownRemark Node. By specifying it in the query as shown below, you can obtain the table of contents data.

query MyQuery {
  markdownRemark(id: { eq: $id }) {
    id
    tableOfContents
    frontmatter {
      title
    }
  }
}

For example, consider a Markdown structure with headers as shown below.

## First
### FirstChild1
### FirstChild2
## Second

Then, the value of tableOfContents would retrieve the following HTML structure string. If no headers exist in the Markdown, an empty string is returned.

"<ul>\n<li>\n<p><a href=\"#first\">First</a></p>\n<ul>\n<li><a href=\"#firstchild1\">FirstChild1</a></li>\n<li><a href=\"#firstchild2\">FirstChild2</a></li>\n</ul>\n</li>\n<li>\n<p><a href=\"#second\">Second</a></p>\n</li>\n</ul>"

This string, when formatted as HTML, looks like the following.

<ul>
  <li>
    <p><a href="#first">First</a></p>
    <ul>
      <li><a href="#firstchild1">FirstChild1</a></li>
      <li><a href="#firstchild2">FirstChild2</a></li>
    </ul>
  </li>
  <li><p><a href="#second">Second</a></p></li>
</ul>

You can display the table of contents within the page as shown below. Now, all that remains is to style it using CSS to complete the table of contents.

<nav dangerouslySetInnerHTML={{ __html: contentsOfTable }} />

Conclusion

I was able to easily display the table of contents without needing a TOC generation library, and it reminded me once again of the convenience of Gatsby.


Related Posts
Related Posts
Promotion

This site uses Google Analytics.