2

I am trying to write a function so I can copy the current browser's url to the clipboard when clicking on a link. I am still trying to understand this code, at this point I don't know how to create an input, set its value to the URL of the current document, select its contents and execute copy, as I understand it is the way to hack it. Right now when clicking on the text I get an error: Cannot read property 'select' of null... Any cue would be appreciated.

export function Copy() {
    const [copySuccess, setCopySuccess] = useState("")
    const textAreaRef = useRef(null)

    function copyToClip(e) {
        //navigator.clipboard.writeText(e.target.getAttribute("href"))
        textAreaRef.current.select()
        document.execCommand("copy")
        setCopySuccess("Copied")
    }

    return (
        <>
            {document.queryCommandSupported("copy") && (
                <Text onClick={copyToClip}>
                    Copy
                </Text>
            )}
        </>
    )
}
Lili
  • 333
  • 4
  • 23

3 Answers3

4

This question is really composed of two:

  1. How to get the current URL in js?
const url = location.href;
  1. How to copy text to clipboard using js?:
navigator.clipboard.writeText(url);

Finally:

export function Copy() {
    const [copySuccess, setCopySuccess] = useState("")
    const textAreaRef = useRef(null)

    async function copyToClip() {
        await navigator.clipboard.writeText(location.href);
        setCopySuccess("Copied");
    }

    return (
        <>
            <Text onClick={copyToClip}>
                Copy
            </Text>
        </>
    )
}
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
0

use this

function test(){
  let urlField = document.createElement('urlField')
    urlField.innerText = "your link here"
    document.body.appendChild(urlField)
    urlField.select()
    document.execCommand('copy')
    urlField.remove()
}

It will create another field to save any text you want and copy it to clipboard, after that it will disappear.

In your code const textAreaRef = useRef(null) textAreaRef has reference to not exist component so it cannot select or append text

Trương Long
  • 100
  • 1
  • 11
  • 2
    `document.execCommand()` is [deprecated](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) and should no longer be used. Use the [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) instead – Chayim Friedman Jan 28 '21 at 03:00
  • Thanks for that, I will update and use it! – Trương Long Jan 28 '21 at 03:17
0
const textareaEl = document.createElement('textarea');
textareaEl.value = window.location.href;
document.body.appendChild(textareaEl);
textareaEl.focus();
textareaEl.select();
document.execCommand('copy');
document.body.removeChild(textareaEl);

In Case you are copying the current URL to the clipboard, you can use the above codes (the number one code), and the following is for the time you are defining a handle click just by adding (number 2 code):

const [copied, setCopied] = useState(false);
function copyTask() { const el = document.createElement('input');
    el.value = window.location.href;
    document.body.appendChild(el);
    el.select(); document.execCommand('copy'); 
    document.body.removeChild(el); setCopied(true);
} 
<Button onClick={copyTask}> {!copied ? 'Copy link' : 'Copied!'} </Button>
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
  • In Case you are copying the current URL to the clipboard, you can use the above codes (the number one code), and the following is for the time you are defining a handle click just by adding (number 2 code): – Sara Asefi Jun 20 '22 at 10:36
  • const [copied, setCopied] = useState(false); function copyTask() { const el = document.createElement('input'); el.value = window.location.href; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); setCopied(true); } – Sara Asefi Jun 20 '22 at 10:43