Autolink Headings
If you have a lot of sections on your page and want to share a link to a specific section, then you will need rehype-autolink-headings plugin to add links from headings back to themselves.
Setup
npm install rehype-slug rehype-autolink-headings
Modify your next.config.js
file to include the plugin:
// next.config.js
import rehypeAutolinkHeadings from "rehype-autolink-headings";
//...
const withMDX = createMDX({
extension: /\.mdx?$/,
options: {
// If you use remark-gfm, you'll need to use next.config.mjs
// as the package is ESM only
// https://github.com/remarkjs/remark-gfm#install
remarkPlugins: [],
rehypePlugins: [
rehypeSlug,
[
rehypeAutolinkHeadings,
{
behavior: 'wrap', // append, prepend
headingProperties: { tabIndex: '-1', dir: 'auto' },
properties: { className: ['heading-link'] }
}
]
],
},
})
//...
Add anchor character
If you now restart your website, you won't see any difference. The anchor links are there, but they don't have any content. You can add content with CSS as follows:
/* ./css/global.css*/
.heading-link::before {
content: '# '; /* § */
}
.heading-link {
color: black;
}