-
-
Save vojty/2898cdd7cca5d4941652d366cea16b7b to your computer and use it in GitHub Desktop.
Get headers from MDX in Next.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {MDXProvider} from '@mdx-js/react'; | |
import {MDXComponents} from 'components/MDX/MDXComponents'; | |
import {Toc} from 'components/Toc/Toc'; | |
import * as React from 'react'; | |
export interface MarkdownProps<Frontmatter> { | |
meta: Frontmatter; | |
children?: React.ReactNode; | |
} | |
export default function MarkdownPage<T extends {title: string} = {title: string}>({ | |
children, | |
meta, | |
}: MarkdownProps<T>) { | |
const anchors = React.Children.toArray(children) | |
.filter( | |
(child: any) => | |
child.props?.mdxType && ['h2', 'h3'].includes(child.props.mdxType) | |
) | |
.map((child: any) => ({ | |
url: '#' + child.props.id, | |
depth: | |
(child.props?.mdxType && | |
parseInt(child.props.mdxType.replace('h', ''), 0)) ?? | |
0, | |
text: child.props.children, | |
})); | |
return ( | |
<> | |
<MDXProvider components={MDXComponents}>{children}</MDXProvider> | |
<Toc anchors={anchors} /> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment