Skip to content

Instantly share code, notes, and snippets.

@iamaamir
Last active November 18, 2022 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamaamir/43dae933412405500b2f4494d68aba0f to your computer and use it in GitHub Desktop.
Save iamaamir/43dae933412405500b2f4494d68aba0f to your computer and use it in GitHub Desktop.
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>
</>
)
}
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