DEV Community

Cover image for Add a "Copy Link to Clipboard" button to your website in 10 lines of code

Add a "Copy Link to Clipboard" button to your website in 10 lines of code

Snappy Web Design
Snappy Web Design is a full service web design + web development company in Ann Arbor, Michigan
Originally published at ・1 min read

Providing your users an easy way to share your blog posts is an SEO no brainer. Using the default Navigator api [navigator.clipboard.writeText] is a common approach, but lacks mobile support.

The best way to copy selected text to the clipboard is by creating a hidden textarea. Luckily, all you need to do is copy the following code:


  onClick={() => {
  Copy Link to Clipboard
Enter fullscreen mode Exit fullscreen mode


const CopyToClipboard = toCopy => {
  const el = document.createElement(`textarea`)
  el.value = toCopy
  el.setAttribute(`readonly`, ``) = `absolute` = `-9999px`
Enter fullscreen mode Exit fullscreen mode


You can easily extend this by displaying an alert to give users success feedback. An example of how this could be done in Material-UI is with a Snackbar and a piece of state to control the snackbar.
Check out the full post on to see how.

Did you find this article helpful?

If you did, would you take a second to share the article? It helps our cause immensely!
Make sure to also click the follow button to get notified when new posts go live 🔔

Discussion (1)

pcjmfranken profile image
Peter Franken

FYI You can use the native clipbloard API writeText method like so navigator.clipboard.writeText(window.location.href) and get rid of the entire hidden textarea function.