Copy the current URL to the clipboard in a React app

Copy the current URL to the clipboard in a React app

Interacting with the clipboard used to be hard as there weren't a lot of great browser APIs.  That's changed now.  Here's how to copy the URL of the current page using React.  You don't really need to use React, but I did.

The basic premise is this:

  1. Create a button that says "copy."
  2. It triggers a copy action.
  3. The copy action creates an invisible element.
  4. Put the text you want to copy into this invisible element.
  5. Select it.
  6. Do the copy.

If it seems hacky, it is, 2021 web technology is not that different in some ways, but I assure you, this is a lot cleaner than things were 10 years ago.

Create the Button

<button onClick={ copy }>Copy URL</button>
Just a JSX button.

If you're new to React and JSX, this is normal button element with an onclick handler that calls a copy() method.  webpack turns this into proper browser legible HTML and JS.

The Copy Action

function copy() {
  const el = document.createElement('input');
  el.value = window.location.href;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
}

So here's our method, copy().  It creates a new element, an input tag.  It sets the value of this tag with the current URL from the browser.  The element needs to be attached to the body of the document such that it can be selected.  Then the browser's copy can be run.  We then remove our element to cleanup.

Some Flair

This works, but let's add a tiny bit of feedback.  Let's change the button to say "copied."  I got this idea from a coworker.

Here's the full example:

The ability to copy in a single-click can easily make a web app feel a bit more "app"-y and less like a cumbersome webpage.  


Show me some cool tricks that were hard to do 10 years ago.  10years@davedash.33mail.com!