1

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
  • 273
  • 2
  • 15

2 Answers2

2

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
  • 14,050
  • 2
  • 21
  • 36
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