When there is a markdown style codeblock within an MDX file it will be processed like markdown, and will result in an html structure like this:
The basic outline to create a copy button is:
- First, store a copy of the code string in the 'pre' html element using an attribute called 'rawstring'. This will be done by some code in the MDX processing pipeline. Mine looks this:
The results after processing a real example code block will look like this (notice the __rawstring__
property added?):
- Next, inside a custom 'pre' component send the data in the 'rawstring' attribute to the copy button component. My custom "pre" component looks like this:
- Finally, within the copy button component, copy the string to the clipboard when the button is clicked. My CopyButton component looks like this:
Rendering MDX Content
There is a little more to it though - your custom components need to be passed to your MDX rendering process. Here's some example code of how to do that. First we will create a const containing our new custom components and then we will setup MDX rendering using the custom components.
Creating a "MDXContent" rendering function:
Rendering a page in Next.js using MDXContent: