A teddy bear, wearing Ray Ban sunglasses, sticking it's head out of an upright piano. A piece of piano music is in the lower right corner.

Link to headers

I thought it would just work! I thought I could just use something like this.

Jump to [Look out behind you](#look-out-behind-you)

Well, it did not just work!

This Works

Creating Linked Blog Post Headers using MDX on GatsbyJS. - Coner Murphy

  • For any header, add this to components in: MdxWrapper.js, gatsby-ssr.js, & gatsby-browser.js
1h2: (props) => (
2 <h2 id={props.children.replace(" ", "-").toLowerCase()}>
3 <a
4 href={`#${props.children.replace(" ", "-").toLowerCase()}`}
5 >
6 {props.children}
7 </a>
8 </h2>
9),
The code supplied will only catch the first space it finds. That works fine for two word headers. What if you are a little silly and right a header like, oh, "Look out behind you". It doesn't work there. Changed it to use RegEx (now I've got two bugs) 😆 Just kidding RegEx!

RegEx: /\s/g - Match any whitespace character in the string globally. It will iteratively search the whole string and replace every occurrence.

1h2: (props) => (
2 <h2 id={props.children.replace(/\s/g, "-").toLowerCase()}>
3 <a
4 href={`#${props.children.replace(/\s/g, "-").toLowerCase()}`}
5 >
6 {props.children}
7 </a>
8 </h2>
9),

These are currently not handled by the MarkdownLink component. As they are internal links, they should look like an Internal link.

1// Not how I normally do this. I'd normally say ../components
2// and I'll probably fix that at some point.
3import { InternalLink } from '.'
4
5export const MarkdownLink = ({ href, ...rest }) {
6 ...
7 if (href.startsWith('#')) {
8 // return <a href={href} {...rest} />
9 return <InternalLink href={href} {...rest} />
10 }
11 ...
12}
Attributions

Photo by Me during a rehearsal with Nineteen

Built with Gatsby from 2020 thru 2024 (and beyond?!)