How to use React Wrap Balancer for MDX headings

May 20, 2023


I wanted to use React Wrap Balancer to improve headings in my MDX blog posts. I could have imported Balancer and put it around all my headings, but I wanted the computer to do that for me.

Initially, I thought a Remark plugin would do the trick, but after a brief search, I couldn't find a plugin that would swap elements with React components.

Shortly after, I found myself on the next-mdx-remote docs, and I discovered something even simpler.

next-mdx-remote provides direct support for replacing elements, so I replaced h2 (and other headings) using the following:

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

<MDXRemote {...source} components={components} />;