Skip to content

Instantly share code, notes, and snippets.

@vojty
Forked from jaredpalmer/MarkdownPage.tsx
Created February 18, 2021 11:40
Show Gist options
  • Save vojty/2898cdd7cca5d4941652d366cea16b7b to your computer and use it in GitHub Desktop.
Save vojty/2898cdd7cca5d4941652d366cea16b7b to your computer and use it in GitHub Desktop.
Get headers from MDX in Next.js
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