Created
November 4, 2023 10:59
-
-
Save GalindoSVQ/9b1f7547f54faca76502f07745a2e4a8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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'; | |
| function oldSchoolCopy(text) { | |
| const tempTextArea = document.createElement('textarea'); | |
| tempTextArea.value = text; | |
| document.body.appendChild(tempTextArea); | |
| tempTextArea.select(); | |
| document.execCommand('copy'); | |
| document.body.removeChild(tempTextArea); | |
| } | |
| export default function useCopyToClipboard() { | |
| const [state, setState] = React.useState<string | null>(null); | |
| const copyToClipboard = React.useCallback((value: string) => { | |
| const handleCopy = async () => { | |
| try { | |
| if (navigator?.clipboard?.writeText) { | |
| await navigator.clipboard.writeText(value); | |
| setState(value); | |
| } else { | |
| throw new Error('writeText not supported'); | |
| } | |
| } catch (e) { | |
| oldSchoolCopy(value); | |
| setState(value); | |
| } | |
| }; | |
| handleCopy(); | |
| }, []); | |
| return [state, copyToClipboard]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Stackblitz link: https://stackblitz.com/edit/vitejs-vite-zhtraw?file=src%2FuseCopyToClipboard.ts