What Are Heading Anchors? If you are not already familiar with heading anchors, check out any README.md on GitHub or hover over a heading within most blog posts and you will likely see a small link icon or hashtag to the left of the title, indicating that you can click to anchor to that specific heading.

If you'd like to link someone to a specific part of a blog post, you can simply click the title you want to send them to and the address bar is automatically populated with an anchor that will link directly to that section.

Why Not Download an Existing Package? There are excellent rehype and remark plugins such as remark-autolink-headings and rehype-slug. If your goal is to get this feature working as quickly as possible, those are great options.

1 2// Markdown.tsx 3import ReactMarkdown from 'react-markdown' 4 5export default function Markdown({ markdown }) { 6 7 const MarkdownComponents: object = { 8 // Code will go here 9 } 10 11 return ( 12 <ReactMarkdown 13 components={MarkdownComponents} 14 > 15 {markdown.content} 16 </ReactMarkdown> 17 ) 18 19} 20

Import generateSlug.ts and Customize the Heading Node

In my blog, I am using the H3 heading for blog post headings. Change this to whatever fits your needs:

1// Markdown.tsx 2import ReactMarkdown from 'react-markdown' 3import generateSlug from '@/utils/generateSlug' 4 5const MarkdownComponents: object = { 6 h3: (props: any) => { 7 const arr = props.children 8 let heading = '' 9 10 for (let i = 0; i < arr.length; i++) { 11 if (arr[i]?.type !== undefined) { 12 for (let j = 0; j < arr[i].props.children.length; j++) { 13 heading += arr[i]?.props?.children[0] 14 } 15 } else heading += arr[i] 16 } 17 18 const slug = generateSlug(heading) 19 return <h3 id={slug}><a href={`#${slug}`} {...props}></a></h3> 20 } 21} 22... 23
https://blog-genffy.oss-cn-hangzhou.aliyuncs.com/LRV_20210603_171955_01_001_d8a306db39.mp4

qwerqwerqwer


By David Doe

06-10-2022