DEV Community

Nicky Meuleman
Nicky Meuleman

Posted on • Originally published at nickymeuleman.netlify.app

One line copy button for the web

TL;DR: The Clipboard API is quite good.

The one line: navigator.clipboard.writeText("potatoes");


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);
    setCopied(true);
    setTimeout(() => setCopied(false), 1000);
  };
  return (
    <div>
      <p>{text}</p>
      <button onClick={copy}>{copied ? "Copied" : "Copy"}</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

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.

While writing to the clipboard can always be done in the active tab using the Clipboard API, reading the clipboard needs to be permitted.

As with many modern APIs, navigator.clipboard is only available on HTTPS pages.

Optional chaining (?. syntax) can not be used on things like window or navigator.
I would have liked to use it, to prevent errors when rendering on the server without a window, but, alas.

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.

Update: It's official.
IE support has ended on June 15, 2022

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.

Top comments (0)