Let me introduce you to a Rehype plugin called rehype-pretty and a syntax highlighter called shiki. These are the two tools we will be using to add beautiful syntax highlighting to our MDX files.
If you're using another way of rendering your Markdown files, you just need to add the plugin to the array of rehype plugins, this can be found in the documentation of the package you're using.
Now that we have the plugin installed and configured, we can start declaring our code blocks. You can declare a code block using 3 backticks (`), like this:
The code above will look something like this when rendered:
To achieve a similar look to the one you see on my blog, you can use the following CSS:
This adds a scrollbar to the code block when it overflows and adds padding to each line.
Now onto configuring the <pre> component in the markdown-components.tsx file.
Warning
If you're using the title="" attribute for your code block, rehype-pretty will create a new <figcaption> component. This will cause 2 <figcaption> components to be rendered. To avoid this, please move the aforementioned component you see in the example above, to figcaption: (props) => () inside of markdown-components.tsx. Though now, you need to make some style adjustments to the component, along with getting the content of the code block for the <CopyButton>.
Feel free to style the components in any way you want. In this example I am using TailwindCSS.
This code uses the react-to-text package to convert the children of the <pre> component to a string and then passes that string to the <CopyButton> component which you need to create yourself.
How it works is actually pretty simple. You just need to provide the text prop to the <CopyButton> component and listen to an onClick event to copy the text to the clipboard.
data-language is the language you've specified in the code block of your MDX
file.
The reason why a react fragment (<></>) is used, is because each code block gets wrapped in a <figure> component. Thus the resulting code will look something like this:
You can highlight lines using {2,7}, this will highlight lines 2 and 7. A range can also be specified using {2-7}, this will highlight lines 2 through 7.
Now you can add syntax highlighting to your MDX files in Next.js. If you have any questions or feedback, please don't hesitate to reach out, I'm always happy to help and improve this guide. Almost everything in this guide can be found in the official documentation of rehype-pretty, make sure to check it out.