Building in Public - 4
Posted On: 2024-07-21
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>
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 🙂