Copy Button

Add a copy button to a code block.

content.md
```js
function lorem(ipsum, dolor = 1) {
const sit = ipsum == null ? 0 : ipsum.sit
dolor = sit - amet(dolor)
return sit ? consectetur(ipsum) : []
}
```
function lorem(ipsum, dolor = 1) {
const sit = ipsum == null ? 0 : ipsum.sit
dolor = sit - amet(dolor)
return sit ? consectetur(ipsum) : []
}

Implementation

First we make the button component:

button.tsx
"use client"
import { Copy, Check } from "lucide-react"
import { useState } from "react"
export function CopyButton({ text }: { text: string }) {
const [copied, setCopied] = useState(false)
return (
<button
className=""
aria-label="Copy to clipboard"
onClick={() => {
navigator.clipboard.writeText(text)
setCopied(true)
setTimeout(() => setCopied(false), 1200)
}}
>
{copied ? <Check size={16} /> : <Copy size={16} />}
</button>
)
}

And then we use it when rendering the code block:

code.tsx
import { Pre, RawCode, highlight } from "codehike/code"
import { CopyButton } from "./button"
async function Code({ codeblock }: { codeblock: RawCode }) {
const highlighted = await highlight(codeblock, "github-dark")
return (
<div className="">
<CopyButton text={highlighted.code} />
<Pre className="" code={highlighted} />
</div>
)
}