next.jsremarkjscontentlayerrehypejs

How to use MDX custom elements in contentlayer


I'm building a site that makes use of Nextjs and Contentlayer to render a bunch of MDX files.

I basically followed this tutorial to get it set up, except I'm going with MDX instead of plain markdown.

I'm using Contentlayer because the standard way of supporting MDX in Next just doesn't fit my use-case very well.

The Next.js MDX docs have a section on Custom elements. It lets you, for example, decide that all your h1s will be rendered with your custom component or whatever.

My question is: Is there a way to set up custom elements when using Contentlayer?

I assume there is some way to configure rehype or remark, I'm new to both of these tools.


Solution

  • Figured it out :)

    The contentlayer docs have a minimal example. I reproduced it here for convenience

    const Page: React.FC<{ post }> = ({ post }) => {
      const MDXContent = useMDXComponent(post.body.code)
      
      return (
        <div>
          {/* Some code ... */}
          <MDXContent components={{ MyButton }} />
        </div>
      )
    }
    

    If you wanted to get MDX to make use of your components for all the things then you could do something like this:

    const components = {
      p: MyTextComponent,
      h1: MyHeading1,
      h2: MyHeading2.
      ...
    
    const Page: React.FC<{ post }> = ({ post }) => {
      const MDXContent = useMDXComponent(post.body.code)
      
      return (
        <div>
          {/* Some code ... */}
          <MDXContent components={ components } />
        </div>
      )
    }
    

    I wanted to replace basically every standard HTML component with a custom component. I found this example useful in seeing what to include in my components data structure.