Skip to main content

What have I copied?

· 2 min read
Filip Tammergård
Software Engineer at Frilans Finans

Click the button to see what's currently in your clipboard:

You have copied:

You haven't copied anything…

How could it know?!

Thanks to the navigator API. I did it in React and TypeScript. We start by writing a function that checks what's currently in the clipboard:

const read = async () => {
try {
const value = await navigator.clipboard.readText()
setClipboard(value.trim())
} catch {
setClipboard("Couldn't show what you copied...")
}
}

We use trim() to avoid showing for example a stray space, since it wouldn't be visible anyway. We save the result in state, which we of course also need to define:

const [clipboard, setClipboard] = useState<string>()

Reading the clipboard is tied to a user gesture (the button click). That's the recommended pattern — browsers want clipboard reads to be initiated by an explicit user action rather than running automatically.

return (
<>
<button onClick={read}>Show what I copied</button>
<p>You have copied:</p>
<p>{clipboard || "You haven't copied anything..."}</p>
</>
)

The full React component looks like this:

import { useState } from "react"

const Clipboard = () => {
const [clipboard, setClipboard] = useState<string>()

const read = async () => {
try {
const value = await navigator.clipboard.readText()
setClipboard(value.trim())
} catch {
setClipboard("Couldn't show what you copied...")
}
}

return (
<>
<button onClick={read}>Show what I copied</button>
<p>You have copied:</p>
<p>{clipboard || "You haven't copied anything..."}</p>
</>
)
}

export default Clipboard

So if you ever wonder what you've copied but refuse to test by pasting somewhere, you can use this page instead!