Table of Contents is a common feature that we usually seen in article. This feature make web visitor much easier to navigate between each section of a webpage article. Here I’m gonna show you how to generate table of contents automatically on your mdx contentlayer blog.
Install rehype-toc plugins
The first step is to install rehype-toc
plugin created by jsdevtools. You can install it with this command.
You’ll probably want to install unified
, rehype-parse
, rehype-stringify
, and rehype-slug
as well.
Edit contentlayer configuration
Next, you need to add rehype-toc
inside your contentlayer configuration files. Here’s the example.
Customize you ToC
If you see the code snippets when I add rehype-toc to my rehypePlugins, I also define my own customization for ToC. Here’s the code.
This customization will wrap our ToC with div element that have class toc
. Inside this div, we have a text element with p
tag that have title
class. Below this p
tag, we will see our ToC content.
And that’s it. Now when you create a new mdx content, ToC will appear in top of your mdx content body. You don’t need to add any extra code to your mdx content to display the ToC, because it generates automatically for all your mdx content.