Home > Software design >  How do I get the copied value on onCopy event in React?
How do I get the copied value on onCopy event in React?

Time:12-23

Suppose I have a long string:

"Jackie has a very big chicken at his farm"

And I highlight "chicken" from the string and hit ctrl C,

It will trigger the handleCopy function passed into onCopy attribute of the element. I want to have the value of the substring or string being copied, in this case, "chicken" For example,

function handleCopy(event){
     //get the copied value here
}

<input value="Jackie has a very big chicken at his farm" onCopy={handleCopy} />

How am I able to achieve this in React?

CodePudding user response:

Use copy will only trigger the on copy event but will not give you the value. You can use the useRef hook to get the value. Please refer the code below.

function App() {
  const inputRef = useRef();
  function handleCopy(event) {
    console.log("copied value :", inputRef.current.value);
  }
  return (
    <div className="App">
      <input
        ref={inputRef}
        value="Jackie has a very big chicken at his farm"
        onCopy={handleCopy}
      />
    </div>
  );
}

Code Sandbox: https://codesandbox.io/s/stoic-robinson-dqmm8p?file=/src/App.js:70-395

CodePudding user response:

You can use copy event and the getSelection method on it as shown in the docs example ...

A sample e.g. below

const App = () => {
  function handleCopy(event) {
    const selection = document.getSelection();
    console.log(selection.toString())
  }
  return (
    <input
      defaultValue="Jackie has a very big chicken at his farm"
      onCopy={handleCopy}
    />
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

  • Related