@react-hook/copy
Version:
A React hook for copying text to the clipboard
63 lines (46 loc) • 1.77 kB
JavaScript
import * as React from 'react';
function _ref2(copied) {
return copied;
}
function useCopy(text) {
const [copied, setCopied] = React.useState(false);
const reset = React.useRef(() => setCopied(false)); // Resets 'copied' if text changes
React.useEffect(() => reset.current, [text]);
function _ref() {
return setCopied(true);
}
function _ref3() {
return setCopied(_ref2);
}
return {
copied,
copy: React.useCallback(() => copyToClipboard(text).then(_ref).catch(_ref3), [text]),
reset: reset.current
};
}
/* istanbul ignore next */
function copyToClipboard(text) {
// uses the Async Clipboard API when available. Requires a secure browing
// context (i.e. HTTPS)
if (navigator.clipboard) return navigator.clipboard.writeText(text); // puts the text to copy into a <span>
const span = document.createElement('span');
span.textContent = text; // preserves consecutive spaces and newlines
span.style.whiteSpace = 'pre'; // adds the <span> to the page
document.body.appendChild(span); // makes a selection object representing the range of text selected by the user
const selection = window.getSelection();
if (!selection) return Promise.reject();
const range = window.document.createRange();
selection.removeAllRanges();
range.selectNode(span);
selection.addRange(range); // copies text to the clipboard
try {
window.document.execCommand('copy');
} catch (err) {
return Promise.reject();
} // cleans up the dom element and selection
selection.removeAllRanges();
window.document.body.removeChild(span); // the Async Clipboard API returns a promise that may reject with `undefined`
// so we match that here for consistency
return Promise.resolve();
}
export default useCopy;