Created
August 6, 2019 06:19
-
-
Save icai/a2a2139582b40b7e46fbc4536449d16c to your computer and use it in GitHub Desktop.
react copy hooks useCopyClipboard
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 { 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); | |
| } | |
| } | |
| ]; | |
| } |
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
| 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