Skip to content

Instantly share code, notes, and snippets.

@alexanderson1993
Created January 28, 2021 21:43
Show Gist options
  • Save alexanderson1993/8538c0f408227bc6f7e95a34f8b35944 to your computer and use it in GitHub Desktop.
Save alexanderson1993/8538c0f408227bc6f7e95a34f8b35944 to your computer and use it in GitHub Desktop.
A component that copies some text to the clipboard when it is clicked.
import * as React from "react";
const CopyToClipboard:React.FC<{text:string} & React.HTMLAttributes<HTMLButtonElement>> = ({text, ...props}) => {
const copyToClipboard = (event:React.MouseEvent<HTMLButtonElement>, str:string) => {
const el = Object.assign(document.createElement('textarea'),{value:str});
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
props.onClick?.(event);
};
return <button {...props} onClick={e=>copyToClipboard(e, text)} />
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment