Copy to Clipboard ButtonLoading saved progress…

Copy to Clipboard Button

Build a "copy" button as a single React component. Next to a read-only code snippet sits a button; clicking it writes the snippet to the system clipboard and, for a beat, confirms it worked by flipping its label to Copied! before reverting to Copy. The write goes through the async Clipboard API, and the confirmation is a small piece of transient state on a timer.

Task

The starter App.tsx renders the snippet and a Copy button in its resting state. Make it interactive:

  1. Hold the state. Track a copied boolean with useState(false).
  2. Copy on click. Call navigator.clipboard.writeText(text). It returns a Promise, so make the handler async and await it (or chain .then). On success, set copied to true.
  3. Confirm, then revert. While copied is true, add the copied class and show Copied!. Start a setTimeout that flips copied back to false after 2000ms.
  4. Survive rapid clicks. Keep the timer id in a useRef and clear the previous one on each click, so a second click restarts the 2s window instead of an old timer resetting the label early.

Examples

  • The page loads showing npm install uiready with a grey Copy button. Clicking it copies the text; the button turns green and reads Copied!.
  • After 2 seconds with no further clicks, the button reverts to the grey Copy.
  • Clicking again mid-window re-copies and restarts the 2s timer — the label never flickers back early.

Notes

  • writeText is async. It returns a Promise; only mark copied after it resolves, so the confirmation reflects a real success.
  • One boolean drives both. The class and the label both derive from copied — don't track them separately.
  • Clear the old timer. Without clearing, overlapping timers make the label revert at the wrong moment.
  • Styling (snippet box, button, the green copied state) is already in styles.css; focus on the state and the timer.
Loading editor…
Loading preview…