Skip to content

Instantly share code, notes, and snippets.

@icai
Created August 6, 2019 06:19
Show Gist options
  • Select an option

  • Save icai/a2a2139582b40b7e46fbc4536449d16c to your computer and use it in GitHub Desktop.

Select an option

Save icai/a2a2139582b40b7e46fbc4536449d16c to your computer and use it in GitHub Desktop.
react copy hooks useCopyClipboard
import { useState } from "react";
import copy from "@utils/copy";
export default function useCopyClipboard(
text: string
): [boolean, (v: boolean) => void] {
const [isCopied, setIsCopied] = useState(false);
return [
isCopied,
(setcopy = true) => {
if (setcopy) {
const didCopy = copy(text);
setIsCopied(didCopy);
} else {
setIsCopied(setcopy);
}
}
];
}
function dynamicNode(text) {
var node = document.createElement("pre");
node.style.position = "fixed";
node.style.fontSize = "0px";
node.textContent = text;
return node;
}
export default function(text) {
var node = dynamicNode(text);
document.body.appendChild(node);
var selection = getSelection();
selection.removeAllRanges();
var range = document.createRange();
range.selectNodeContents(node);
selection.addRange(range);
document.execCommand("copy");
selection.removeAllRanges();
document.body.removeChild(node);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment