Anchors for headings in MDX

This post was originally published on https://tomekdev.com/posts/anchors-for-headings-in-mdx. What you see as GIF here is interactive there. ✌️

How to add anchors to headings in MDX? It’s surprisingly easy to do. I assume you are already familiar with MDX so somewhere in your code you should have a blog page layout component that uses <MDXProvider>, like that:

MDX consists of components itself. So if there is a code like this then the interpreter changes the inner value (children) into the same content but wrapped with <code></code>.

The same applies to all the headings, lists, paragraphs, etc. Our job is to override the headings. We can do it by passing components hash and specifying a replacement.

Please notice that we are not going to add an anchor to the <h1> tag. It doesn't make sense in my opinion. <h1> is like a summary of the whole page. The URL that links to it is the direct link to the post. Anchors should be used to specific parts of a post (to a section).

Override heading component

The override for <h2> that shows an anchor when the mouse is over the text could look like this:

Below you’ll see the demo. Please notice the hover state. On the left you should see § sign that is also a link, representing our anchor:

Let’s explain a few bits. The way we use headings in Markdown is by using # sign, for example:

Everything that goes after ## is passed as a child to the H2 component.

So the next interesting bit is done in the getAnchor function. Take a look at lines 3 to 8. This is what happens:

  • line 5 — we convert the input to lower case → “i’m h2 with an anchor”
  • line 6 — we remove all non-alphanumeric characters → “im h2 with an anchor”
  • line 7 — we replace spaces with a hyphen → “im-h2-with-an-anchor”

… and voilà. We have a URL-friendly anchor 🎉

The styling

Another important thing here is the CSS. We want to show the anchor only on hover and somewhere next to the heading itself:

Of course, you can go crazy with your anchors ;) That one is very basic.

Recommendation

One thing that is easy to overlook here (in my example) is using a character like § inside of <h2> tag. In this approach, the sign will become a part of the document outline. Which is not something we want. It's better to use an icon in SVG format for example but I didn't want to complicate the example.

If the simple sign is what you want then you should render <a> tag before or after the <h2>.

I connect humans and machines. Usually write about interfaces, digital products, and UX on tomekdev.com. Founder of checknlearn.com. A bit nerdy 🤓