3

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>
            )}
        </>
    )
}

3 Answers 3

6

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>
        </>
    )
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

document.execCommand() is deprecated and should no longer be used. Use the Clipboard API instead
Thanks for that, I will update and use it!
1
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>

2 Comments

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.