From 3b80f4fe79f53c8ea67b699b2d377458bd605fdc Mon Sep 17 00:00:00 2001 From: Paulo Date: Thu, 19 Aug 2021 14:02:45 +0100 Subject: [PATCH] Implement copy support (#12) * Implement copy support * Remove unused import --- README.md | 30 ++++++++++++-------- src/index.ts | 2 ++ src/utils/getCurrentUrlAndCopyToClipboard.ts | 26 +++++++++++++++++ 3 files changed, 46 insertions(+), 12 deletions(-) create mode 100644 src/utils/getCurrentUrlAndCopyToClipboard.ts diff --git a/README.md b/README.md index a5efcde..d7c7ec1 100755 --- a/README.md +++ b/README.md @@ -199,24 +199,16 @@ Example usage: import { getShareUrl, SocialPlatforms } from "@phntms/react-share"; const Share = () => ( - + Share to Facebook - + Share to Linkedin - + Share to Twitter - + Share to WhatsApp ); @@ -224,6 +216,20 @@ const Share = () => ( export default Share; ``` +### getCurrentUrlAndCopyToClipboard() + +Method used to copy current window URL and copy it into your clipboard. + +```jsx +import { getCurrentUrlAndCopyToClipboard } from "@phntms/react-share"; + +const Copy = () => ( +
getCurrentUrlAndCopyToClipboard()}>Copy
+); + +export default Copy; +``` + ## Further Resources Useful resources for testing meta properties: diff --git a/src/index.ts b/src/index.ts index 7b10dff..11adbf9 100755 --- a/src/index.ts +++ b/src/index.ts @@ -26,4 +26,6 @@ export { AllSocialPlatformProps, } from "./utils/getShareUrl"; +export { default as getCurrentUrlAndCopyToClipboard } from "./utils/getCurrentUrlAndCopyToClipboard"; + export { SocialPlatforms } from "./types"; diff --git a/src/utils/getCurrentUrlAndCopyToClipboard.ts b/src/utils/getCurrentUrlAndCopyToClipboard.ts new file mode 100644 index 0000000..9780ce1 --- /dev/null +++ b/src/utils/getCurrentUrlAndCopyToClipboard.ts @@ -0,0 +1,26 @@ +const fallbackCopyToClipboard = (url: string) => { + const placeholder = document.createElement("textarea"); + placeholder.value = url; + + // Avoid scrolling to bottom + placeholder.style.top = "0"; + placeholder.style.left = "0"; + placeholder.style.position = "fixed"; + + // Append element, and focus + document.body.appendChild(placeholder); + placeholder.focus(); + placeholder.select(); + + // Finally, remove element after copy + document.body.removeChild(placeholder); +}; + +export const getCurrentUrlAndCopyToClipboard = () => { + const url = window.location.href; + if (!navigator.clipboard) fallbackCopyToClipboard(url); + else navigator.clipboard.writeText(url); + return url; +}; + +export default getCurrentUrlAndCopyToClipboard;