Add a COPY button to the syntax highlighter

Learn how to enhance your code snippets with a COPY button in your syntax highlighter. This guide provides a step-by-step solution to implement a user-friendly copy feature, improving code sharing and readability.

How to Add a COPY Button to the Syntax Highlighter

Maintaining our MDX system requires access to fs. Without it, we might need to consider transitioning to a database. The idea of adding a copy button presented two possible approaches:

  1. Integrating a button during the markdown-to-highlighter conversion process, enabling direct code copying.
  2. Adding a button that copies the content client-side, which might conflict with other elements of our setup.

To avoid complicating our system with a database or an external service, I opted for what I believe to be an adequate workaround.

Step-by-Step Solution

Step 1: Introduce the CSS

Add the following CSS to your stylesheet to create a visual indicator when the button is active:

.copyButton:active::after {
  content: ' ✅';
  display: inline;
}

Step 2: Implement the Copy Button

Use the following code to implement the actual workaround:

const result = match ? (
  <div>
    <a
      className="copyButton"
      href={`javascript:navigator.clipboard.writeText(${JSON.stringify(
        children
      )})`}
    >
      Copy
    </a>
    <SyntaxHighlighter language={match[1]} style={dracula}>
      {String(children).replace(/\n$/, '')}
    </SyntaxHighlighter>
  </div>
) : (
  <code className={className} {...props}>
    {children}
  </code>
);


## Alternative Approach and Edit (2024-04-19)

Another option to consider is performing the copy action using a selector and then copying from `textContent`. However, when I tried this, it didn't preserve spacing properly and resulted in a single line of code.

Ultimately, I believe the best solution is to use a button to copy the code block. It offers a straightforward and user-friendly approach.
← Back to posts

We use cookies to improve your experience and analyze our traffic. By using our site, you consent to our use of cookies. You can manage your preferences below: