Add a Dynamic Table of Contents to Your Markdown Documents with remark-toc

John Otander
InstructorJohn Otander
Share this video with your friends

Social Share Links

Send Tweet

Manually maintaining a table of contents in markdown documents can be a lot of work. By combining remark-toc and remark-slug you can ensure generate your table of contents and ensure it's always up to date.

John Otander: [00:00] In order to generate a dynamic table of contents in our markdown document, we'll need to install the Remark Toc library. When that's complete we can begin editing our build script.

[00:10] As you can see we're currently invoking Remark and passing at the remark html plugin. We'll also need to require the Remark Toc plugin and pass it to Remark as well.

[00:20] Remark Toc uses a special heading in your document in order to know where to place the table of contents. We'll go ahead and add that.

[00:27] Now we can rerun our build with yarn start and refresh the html page. Our table of contents has been added and generated based off the headings in our document. However, the links do not work.

[00:43] If we inspect the table of contents links we see that there's a slugified ID that we're linking to. However, those IDs are not being added to the headings.

[00:53] In order to slugify our headings, we can use the Remark Slug plugin. After we yarn install the library, we can require it and then pass it to remark as well. After we run our build to the yarn start, we'll see that the h2 now has a slugified ID. This ensures that our table of contents links now work.

[01:12] Altogether, we used the remark Toc library to generate a dynamic table of contents based on headers. Then we used Remark Slug to slugify the headings. This results in a fully functional, linkable table of contents.