Custom MDX headings with rehype-slug

May 22, 2023


When I added rehype-slug to my Next.js project, it didn't seem to be working right. No ids were being added to my headings.

I then remembered I was using custom components for headings, since I wanted to put a <Balancer> inside them.

I inspected the compiled MDX, and saw that rehype-slug was adding ids to headingsā€”but when that compiled MDX was passed to <MDXRemote>, the headings were being replaced with my custom component, losing the id in the process.

All I had to do to fix it was pass the id through to my custom component:

const components = {
	h2: (props: { id?: string; children?: ReactNode }) => (
		<h2 id={props.id}>
			<Balancer>{props.children}</Balancer>
		</h2>
	),
	// ...
};