Button Copy to Clipboard window location href

  javascript, react-hooks, reactjs, window

I want to copy the current window.location.href onClick in the button, even if i set the right state i can not actually copy it, what is my problem?

Here the code

const [copyHref, setCopyHref] = useState(JSON.stringify(window.location.href));

  const copyToClipboard = () => {
    setCopyHref(copyHref)
    document.execCommand(copyHref);
    alert("Copied the text: " + copyHref);
  };

<Button onClick={copyToClipboard}/>

When i click i get the alert with the right url, but it does not actually copy it. How can i do that?

Source: Ask Javascript Questions

LEAVE A COMMENT