• Date

  • By

    • Nicky Meuleman
  • Tagged

  • Older post

    The Sieve of Eratosthenes

  • Newer post

    Concurrent vs parallel

Table of contents
  1. Browser support

One line copy button for the web

Copying something to the clipboard can be done in one line now. The Clipboard API is what powers this. It has a bunch of asynchronous methods, meaning they return promises. The promise resolves? Neat, do things afterwards.

This example React component uses the writeText method to copy a string to the clipboard.

import { useState } from "react";
const CopyDemo = () => {
const text = "Boil em, mash em, stick em in a stew.";
const [copied, setCopied] = useState(false);
const copy = async () => {
await navigator.clipboard.writeText(text);
setTimeout(() => setCopied(false), 1000);
return (
<button onClick={copy}>{copied ? "Copied" : "Copy"}</button>

After adding some CSS, that looks like this:

Boil em, mash em, stick em in a stew.

If you prefer vanilla JS, check out my copy button codepen.

Click the copy button and BAM, Samwise Gamgee’s words of wisdom are now in the clipboard.

Browser support

This is available in all major browsers browsers, except Interner Explorer.

With Microsoft ending Internet Explorer support for some of their own major products. And planning to deprecate it further in 2021, I’m not worried about Internet Explorer lacking support for the clipboard API.

The Clipboard API is meant to replace the old way of accessing the clipboard via document.execCommand(). execCommand() is deprecated, only to be used for compatibility purposes.

Designed and developed by Nicky Meuleman

Built with Gatsby. Hosted on Netlify.