Created
January 28, 2021 21:43
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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