I recently revamped my site and I was looking for a way how to do my own copy code button for code snippets. I wanted something clean, simple and provides user with feedback.
After a bit of consulting the main man google, I could not find any good examples using a similar tech stack. So back to the drawing board.
Then I realised that I could make my own custom pre component.
In this example I am going to be using:
Here is a good starting point if you would like to do the same.
Section titled SetupSetup
Let’s start with this.
Then add that to my MDXComponents.
Then pass the custom components into the MDXRemote.
Right now, you won’t notice any difference as we have only replicated the default behaviour.
Section titled ImplementationImplementation
We want the copy button to be top right even when the pre will overflow, so we will start by wrapping the pre in a div.
Then create a div inside our pre and position that top right
So we can prove the user with some feedback lets add some state and add an onClick={onClick}
event to the button.
In my case I also want to reset the user feedback after 2 seconds.
Now we need to implement some way of copying text into the clipboard. I originally thought of using react-copy-to-clipboard but I don’t have access to the text only the react components.
I manged to come up with a nice work around by using ref and innerText.
First we need to create a ref const preRef = useRef(null)
then hook that up to the pre element.
Let’s create our custom copy to clipboard function. I wanted to support newer writeText
API and a fall back just in case it was not supported.
Now let’s add that to our onClick event.
After that you should have something useable, then you can add styling based on state etc.
You can find my full code here
Section titled ConclusionConclusion
Creating your own copy code button is a great way to customize it and adds a better user experience. I hope with my examples above using MDXRemote and Tailwind, you can create something for your own blog.
Happy coding! 👋