Last active
November 18, 2022 08:52
-
-
Save iamaamir/43dae933412405500b2f4494d68aba0f to your computer and use it in GitHub Desktop.
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
export default function Copy() { | |
const [value, copytoClipboard] = useCopyToClipboard(); | |
const copy = txt => () => copytoClipboard(txt); | |
return ( | |
<> | |
<h1>Click to copy:</h1> | |
<div> | |
<button onClick={copy('A')}>A</button> | |
<button onClick={copy('B')}>B</button> | |
<button onClick={copy('C')}>C</button> | |
</div> | |
<p>Copied value: {value ?? 'Oops something went wrong'}</p> | |
</> | |
) | |
} |
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 { useState } from 'react'; | |
function useCopyToClipboard() { | |
const [copiedText, setCopiedText] = useState(null); | |
const copy = async (text) => { | |
if (!(navigator === null || navigator.clipboard)) { | |
console.warn('Clipboard not supported'); | |
return false; | |
} | |
// Try to save to clipboard then save it in the state if worked | |
try { | |
// or call the service here | |
// ClipboardHelper.copy(text); | |
await navigator.clipboard.writeText(text); | |
setCopiedText(text); | |
return true; | |
} | |
catch (error) { | |
console.warn('Copy failed', error); | |
setCopiedText(null); | |
return false; | |
} | |
}; | |
return [copiedText, copy]; | |
} | |
export default useCopyToClipboard; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment