Rehypre-pretty-code - built-in copy button

shiki copy button within pre code tag

image loading ...

Test

function helloWorld() 
  console.log('Hello, world!');

Mission

Rehype-pretty-code includes a built-in copy 'button' plugin, but it run into following issues with Next.js 14.

Github issue - Error: Expected onClick listener to be a function, instead got a value of string type.

import { transformerCopyButton } from "@rehype-pretty/transformers";
 
mdx: {
    rehypePlugins: [
      rehypeSlug,
      [
        rehypePrettyCode,
        {
          theme: "github-light",
          transformers: [
            transformerNotationDiff(),
            transformerCopyButton({
              visibility: "always",
              feedbackDuration: 5_000,
            }),
          ],
        },
      ]
onClick={() => this.props.addCharacterById(character.id)}

Solution

const handleCopy = async () => {
    const textToCopy = getTextFromChildren(children);
 
    try {
      await navigator.clipboard.writeText(textToCopy);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy!", err);
    }
  };
 

Reference

Rehype-pretty : Copy button

copy-button.ts