70 %
Chris Biscardi

A modern copy button

Implementing copy-to-clipboard functionality has gotten so much easier than it used to be. We can take advantage of writeText in all modern browsers (except Safari as of the time of writing. If you need legacy browser support, here is a useful package).

Here is a Preact/React component that accepts any value and lets a user copy it. It is very important that the writeText call happens in response to a user action in an event handler, or you'll incur the cost of asking the user for permission first.

JS
const CopyButton = props => {
const [buttonText, setText] = useState("Copy");
return (
<button
onClick={e => {
navigator.clipboard.writeText(props.content);
setText("Done");
setTimeout(() => {
setText("Copy");
}, 1000);
}}
>
{buttonText}
</button>
);
};

Tell someone else about this on Twitter