0

I am trying to achieve copy to clipboard functionality, which is working fine if I pass type of button to text i.e. type="text", but not working when the type of button hidden. Here is the link for the codeSandbox https://codesandbox.io/s/priceless-blackburn-irwvw?file=/src/App.js

Note:- Don't want to hide the input with CSS. Please help me to find a solution for that. Thanks in advance.

import React, { useRef, useState } from "react";

export default function App() {
  const inputRef = useRef(null);
  const [copied, setCopy] = useState(false);

  const copy = () => {
    setCopy(false);
    inputRef.current.focus();
    inputRef.current.select();
    try {
      const successful = document.execCommand("copy");
      if (successful) {
        setCopy({ copied: "Link Copied!" });
      }
    } catch (err) {
      console.log("err=>", err);
      setCopy({ copied: err });
    }
  };

  return (
    <div className="App">
      <button onClick={copy}>Copy </button>
      <input
        ref={inputRef}
        defaultValue={"https:www.google.com"}
        type="hidden"
      />
    </div>
  );
}
  • How can one select text in a hidden input? You might have to use CSS in this scenario. – evolutionxbox Jun 22 '20 at 16:40
  • Does this answer your question? [Using execCommand (Javascript) to copy hidden text to clipboard](https://stackoverflow.com/questions/31593297/using-execcommand-javascript-to-copy-hidden-text-to-clipboard) – evolutionxbox Jun 22 '20 at 16:43
  • Is there any way to do that with hidden field, actually don't want to show input box on the ui – abhishek gupta Jun 22 '20 at 16:43
  • @shai_sharakanski's link is good. Specifically this answer https://stackoverflow.com/a/61167333/989920 – evolutionxbox Jun 22 '20 at 16:46

1 Answers1

0

with Clipboard.writeText you can do it.

const { useState, useRef, useEffect } = React;

function App() {
  const inputRef = useRef(null);
  const [copied, setCopy] = useState(false);

  const copy = () => {
    setCopy(false);
    const value = inputRef.current.value;
    
    navigator.clipboard.writeText(value)
      .then(result => {
        setCopy({ copied: "Link Copied!" });
      })
      .catch(err => {
        setCopy({ copied: err });
      })
  };

  return (
    <div className="App">
      <button onClick={copy}>Copy </button>
      <input
        ref={inputRef}
        defaultValue={"https:www.google.com"}
        type="hidden"
      />
    </div>
  );
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

<div id="root"></div>
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50