Create a Simple MDX Table of Contents in Contentlayer

Add a simple table of contents component to your contentlayer mdx content with rehype plugins.

📆 September 2022, 24

⏳ 2 min read

  • # mdx
  • # contentlayer

A Table of Contents is a common feature that we usually see in articles. This feature makes it much easier for web visitors to navigate between each section of a webpage article. Here I’m going to show you how to generate a table of contents automatically on your MDX Contentlayer blog.

Install rehype-toc plugins

The first step is to install the rehype-toc plugin created by jsdevtools. You can install it with this command.

Terminal window
npm install @jsdevtools/rehype-toc

You’ll probably want to install unified, rehype-parse, rehype-stringify, and rehype-slug as well.

Terminal window
npm install unified rehype-parse rehype-stringify rehype-slug

Edit Contentlayer configuration

Next, you need to add rehype-toc inside your Contentlayer configuration files. Here’s an example.

contentlayer.config.ts
import rehypeToc from "@jsdevtools/rehype-toc";
const contentLayerConfig = makeSource({
contentDirPath: "src/contents",
documentTypes: [Post, Project],
mdx: {
remarkPlugins: [remarkGfm],
rehypePlugins: [
rehypeCodeTitles,
rehypeSlug,
[rehypeToc, { customizeTOC }], // add rehypeToc and customization
],
},
});

Customize your ToC

If you see the code snippet where I add rehype-toc to my rehypePlugins, I also define my own customization for the ToC. Here’s the code.

const customizeTOC = (toc: RehypeElement): RehypeElement | null => {
try {
const { children } = toc;
const childrenOfChildren = children?.[0]?.children;
if (!children?.length || !childrenOfChildren?.length) return null;
} catch (e) {}
return {
type: "element",
tagName: "div",
properties: { className: "toc" },
children: [
{
type: "element",
tagName: "p",
properties: { className: "title" },
children: [
{
type: "text",
value: "Table of Contents",
},
],
},
...(toc.children || []),
],
};
};

This customization will wrap our ToC with a div element that has the class toc. Inside this div, we have a text element with a p tag that has the title class. Below this p tag, we will see our ToC content.

And that’s it. Now when you create new MDX content, the ToC will appear at the 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.

Edit this page Tweet this article