DEV Community

Bryan Liao
Bryan Liao

Posted on • Originally published at bryanliao.dev

Building in Public - 4

Continuing my data export journey from last time, I wanted to learn how to copy data to a clipboard. It’s a simple feature, but I always appreciate it when a site has click to copy buttons for code blocks, API keys, etc.

There’s a navigator object within the browser that contains access to the clipboard API. Using this API, one can copy designated text to the user’s clipboard (and paste too)! Here’s a simple implementation that I added to my app that utilized the writeText() function:

const context = {
    users: [{
        'id': 123,
        'name': 'user1'
        },
        {
        'id': 321,
        'name': 'user2'
        },
    ],
};

  const copyDataToClipboard = () => {
    navigator.clipboard.writeText(JSON.stringify(context)).then(() => {
      const copyButton = document.getElementById('copyButton');
      copyButton.innerHTML = 'Copied!';
      setTimeout(() => {
        copyButton.innerHTML = 'Click to copy data';
      }, 3000);
    });
  };

<button id='copyButton' onClick={() => copyDataToClipboard()}>Click to copy data</button>
Enter fullscreen mode Exit fullscreen mode

There’s an added bonus that it may feel safer to copy something to your clipboard and paste it into your own text file than to download one directly from a website 🙂

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️