Skip to content

Unable to get rehype-pretty-code working with rehype-mdx-code-props in next-mdx-remote setup #253

@weepaho3

Description

@weepaho3

I'm trying to configure rehype-pretty-code alongside rehype-mdx-code-props in a next-mdx-remote setup but haven’t managed to get it to work as expected. I'm aiming to enable syntax highlighting with custom props for code blocks in MDX files, but I’m not seeing the expected output.

Setup Details:
Here’s my current configuration:

interface Frontmatter {
  title: string;
  description: string;
}

const { content, frontmatter } = await compileMDX<Frontmatter>({
  source: markdown,
  options: {
    parseFrontmatter: true,
    mdxOptions: {
      rehypePlugins: [
        [
          rehypePrettyCode,
          {
            theme: 'github-dark-default',
            keepBackground: false,
          } as Options,
          rehypeMdxCodeProps,
        ],
      ],
    },
  },
  components: components,
});

My MDX Components:

export const components = {
pre: ({ children, ...props }: React.HTMLAttributes<HTMLPreElement>) => (
  <pre
    {...props}
    className='bg-foreground max-h-[450px] overflow-x-auto rounded-lg border'
  >
    {React.Children.map(children, (child) => {
      if (React.isValidElement(child)) {
        return React.cloneElement(child, { isBlock: true } as unknown as boolean);
      }
      return child;
    })}
  </pre>
),
code: ({
  className,
  filename,
  children,
  isBlock,
  ...props
}: React.HTMLAttributes<HTMLElement> & { isBlock?: boolean; filename?: string }) => {
  if (!isBlock) {
    return (
      <code
        {...props}
        className={`bg-muted rounded px-1 py-0.5 font-mono text-sm ${className}`}
      >
        {children}
      </code>
    );
  }

  return (
    <>
      <div className='bg-muted flex items-center justify-between py-1 pl-2 pr-1'>
        <span>{filename}</span>
        <CopyButton textToCopy={children ? children.toString() : ''} />
      </div>
      <pre
        {...props}
        className={`relative rounded-lg p-4 font-mono text-sm ${GeistMono.className}`}
      >
        {children}
      </pre>
    </>
  );
},

MDX

```tsx filename="index.tsx"
console.log('hello world');
```

I’m not a developer, so I apologize if this is a basic question. I’d appreciate any insights or tips to get this working. Could it be an issue with the plugin order, or do I need to handle props differently?

Expected Behavior:

  • The filename prop should be rendered in a header above each code block.

Thank you in advance for your help!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions