Why you should link to headings in your articles
You may have come across this pattern in articles and posts on sites you frequent - article headings (think <h1>, <h2>, <h3>, <h4>, <h5>, and <h6> in html) will be be wrapped in links that point to themselves. This allows readers to link to specific headings in your articles, jumping to relevant bits of content without forcing someone to read through an entire article. Generally speaking, it will look something like this:
1<a href="#some-unique-id">2<h1 id="some-unique-id">My first blog post</h1>3</a>
The <a> tag here has an href value of #some-unique-id - this is the id of the heading tag. This is based on an HTML standard defined by the W3C. In short, you can link to any element on an HTML page which has a unique id attribute defined, by appending #[id] to the end of the URL, like www.example.com#id-of-the-element.
This is tricky with Markdown and MDX
In most static site generators and JAMStack frameworks which allow you to use Markdown and MDX to generate content, the goal is simple: give authors a very simple way to author content using Markdown syntax. The unfortunate side effect in this case is that there's not a way to specify IDs for the headings in Markdown posts (at least, not one that I'm aware of).
A sample markdown post might look like this:
1---2title: Hello, world3---45# A fish called wanda67In this essay, I will explain the difference between...
This results in the following output:
1<h1>A fish called wanda</h1>2<p>In this essay, I will explain the difference between...</p>
Fantastic! That's a nice, easy way to write, but there's not a way to add an id to the heading tag. At least, not out of the box. This is where MDX's plugins come in handy.
Automatically linking to headings in your mdx posts with rehype plugins
Note: This tutorial assumes you're using MDX with NextJS, althought it may be applicable to other systems. Feel free to send me any hurdles you encounter with other frameworks, and I'll try to document them here.
Step 1: Generate IDs for all headings automatically with rehype-slug
rehype-slug is a plugin that works with MDX, and will automatically generate IDs for your headings by generating a slug based on the text they contain.
-
Install rehype-slug in your project by running npm install --save rehype-slug or yarn add rehype-slug
-
Add rehype-slug to the list of rehype plugins MDX uses. In the case of next.js sites, it is likely wherever you call serialize() from next-mdx-remote.
1import rehypeSlug from 'rehype-slug';23// ...45const options = {6mdxOptions: {7rehypePlugins: [8rehypeSlug, // add IDs to any h1-h6 tag that doesn't have one, using a slug made from its text9],10},11};1213const mdxSource = await serialize(post.content, options);1415// ...
Note: My site uses serialize() in several places, so I extracted options to its own file. This avoids repeated code, and allows me to manage my plugins for MDX from one place.
At this point, if you fire up your dev environment, and use your browser devtools to inspect any of the headings generated from markdown for your site, they should all have an id property added. For the example above, you'd see:
1<h1 id="a-fish-called-wanda">A fish called wanda</h1>
We're halfway there - you can now link to www.example.com#a-fish-called-wanda, and the browser will automatically scroll to the heading.
Step 2: use MDXProvider to customize the way heading tags render
MDXProvider is a wrapper component which allows you to customize the way your MDX renders by providing a list of components.
This step will depend heavily on the UI frameworks you've chosen for your site - I use Chakra UI for my nextjs site, but you can use whatever you like - tailwindcss, Material UI, etc will all have similar parallels.
Here's a simplified version of the code, which I'll show just for <h1> - you'd want to extend this for all title tags, i.e. <h1> through <h6>:
1import Link from 'next/link';23const CustomH1 = ({ id, ...rest }) => {4if (id) {5return (6<Link href={`#${id}`}>7<h1 {...rest} />8</Link>9);10}11return <h1 {...rest} />;12};1314const components = {15h1: CustomH1,16};1718// this would also work in pages/_app.js19const Layout = ({ children }) => {20return <MDXProvider components={components}>{children}</MDXProvider>;21};
Doing it with Chakra UI
Like I mentioned above, my site uses Chakra UI to compose page layouts. I've added a bit of customization to links on my site - including a hover behavior which adds a nice # character before headings when they're hovered over. If you're curious about my implementation with Chakra UI, it looks a bit like this:
1import NextLink from 'next/link';2import { Link, Heading } from '@chakra-ui/react';34const CustomHeading = ({ as, id, ...props }) => {5if (id) {6return (7<Link href={`#${id}`}>8<NextLink href={`#${id}`}>9<Heading10as={as}11display="inline"12id={id}13lineHeight={'1em'}14{...props}15_hover={{16_before: {17content: '"#"',18position: 'relative',19marginLeft: '-1.2ch',20paddingRight: '0.2ch',21},22}}23/>24</NextLink>25</Link>26);27}28return <Heading as={as} {...props} />;29};3031const H1 = (props) => <CustomHeading as="h1" {...props} />;32const H2 = (props) => <CustomHeading as="h2" {...props} />;33const H3 = (props) => <CustomHeading as="h3" {...props} />;34const H4 = (props) => <CustomHeading as="h4" {...props} />;35const H5 = (props) => <CustomHeading as="h5" {...props} />;36const H6 = (props) => <CustomHeading as="h6" {...props} />;3738const components = {39h1: H1,40h2: H2,41h3: H3,42h4: H4,43h5: H5,44h6: H6,45};4647// ...etc - components is passed to MDXProvider in my Layout component
The Result
The result is what you see on this page, and any of the other posts on my site! Every heading on my markdown pages contains an ID, and is wrapped in a link to itself. This makes it easy for readers to tap on the link to send it to their URL bar, or to right-click/long-press and copy a link to the part of the article they want to link to.
The final markup looks a bit like this:
1<a href="#a-fish-called-wanda">2<h1 id="a-fish-called-wanda">A fish called wanda</h1>3</a>
I hope you found this helpful! If you run into any trouble, feel free to drop me a line on twitter. Beyond that, I'd love it if you shared this post with someone who you think could benefit from it.
Auto-linking headings with other frameworks
- Generic HTML and JavaScript - if you're looking for a platform-agnostic solution, you may want to check out this CSS Tricks Article, On Adding IDs to Headings
- Jekyll - a reader was kind enough to send me a tutorial for the same functionality in Jekyll. Check it out on David Darnes' site here: Adding heading links to your Jekyll blog
- 11ty - There doesn't seem to be a standard practice for this pattern with 11ty, but there was a great discussion on ways this might be implemented with plugins and shortcodes in this GitHub Issue: Support generating IDs for headings, for section direct links
- Gatsby - Gatsby has a plugin which supports this behavior, called gatsby-remark-autolink-headers
More reading
If you found this helpful, you may also be interested in: