Zach Schnackel

MDX link routing in Gatsby

In my last article, I wrote about how I was able to parse frontmatter through MDX in Gatsby for a more powerful writing/developer experience. I also mentioned a few remark plugins I brought in-house. Today, I'll walkthrough how I was able to remove three dependencies for just a few lines of code.

Creating links in Markdown is fairly straightfoward:

With the help of a few plugins, we're able to make these links do a bit more for us automagically:

  1. remark-external-links: Automatically adds target and rel attributes to external links.
  2. remark-relative-links: Rewrites absolute URLs to relative ones.
  3. gatsby-plugin-catch-links: Intercepts local links and replaces their behavior with that of the gatsby-link navigate.

With MDX's ability to override normal DOM elements, I was able to encapsulate the logic from all three of these plugins into a handy snippet:

MarkdownLink.js

This can then be passed into <MDXProvider /> to override default links:

Article.js

Since our Markdown links are now powered by a React component, we can apply any other special formatting or logic as needed. Take a look at this one and others I've added to my own site in my shortcodes file. 🎉

:: Published Apr 3, 2020 ::