Skip to content

Instantly share code, notes, and snippets.

@jaredpalmer
Created February 17, 2021 13:52
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jaredpalmer/b437cefc503f876faabb34eb04ad176f to your computer and use it in GitHub Desktop.
Save jaredpalmer/b437cefc503f876faabb34eb04ad176f 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} />
</>
);
}
@mdavish
Copy link

mdavish commented Oct 25, 2023

Hey Jared - how would you get this to work with the app router?
https://nextjs.org/docs/app/building-your-application/configuring/mdx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment