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 , like that:

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

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

Please notice that we are not going to add an anchor to the tag. It doesn't make sense in my opinion. 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 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:

Anchor demo — show on hover
Anchor demo — show on hover

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 component.

So the next interesting bit is done in the 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 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 tag before or after the .

--

--

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tomek Niezurawski

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