Search code examples
javascriptreactjscopy-pastepastecut

Cut and Paste Buttons working on 1st use of both but after doing it one after another then nothing happens in react js with hooks and anchor tag btn


this part of the code is safe used

const [text, setText] = useState("Enter text here");

this is a code of paste function

const inputToPaste = () => {
  navigator.clipboard.readText().then((inputX) => {
    document.getElementById("Textbox").value = inputX;
  });
};

this is code of a cut function

const inputToCut = () => {
  navigator.clipboard.writeText(text);
  const userInput = "";
  setText(userInput);
};

the text area :

<textarea
  onChange={handleOnChange}
  value={text}
  id="Textbox"
  rows="10"
  className="relative mt-10 border-4 max-h-72 min-h-0 border-green-400 text-white bg-gray-600 w-[55rem] max-w-screen-lg h-64 p-2 border-lime-100 rounded-lg focus:outline-none focus:shadow-outline-blue-500"
></textarea>

both btn :

<a
  onClick={inputToCut}
  href="#_"
  className="relative inline-flex items-center justify-start px-4 py-2 overflow-hidden font-semibold transition-all bg-green-400 rounded-md hover:bg-gray-900  active:scale-95 group"
>
  <span className="w-48 h-48 rounded rotate-[-40deg] bg-gray-900 absolute bottom-0 left-0 -translate-x-full ease-out duration-500 transition-all translate-y-full mb-9 ml-9 group-hover:ml-0 group-hover:mb-32 group-hover:translate-x-0"></span>
    <span className="relative w-full text-left text-gray-900 transition-colors duration-300 ease-in-out group-hover:text-green-400">
      Cut
    </span>
  </a>
  <a
    onClick={inputToPaste}
    href="#_"
    className="relative inline-flex items-center justify-start px-4 py-2 overflow-hidden font-semibold transition-all bg-green-400 rounded-md hover:bg-gray-900  active:scale-95 group"
  >
    <span className="w-48 h-48 rounded rotate-[-40deg] bg-gray-900 absolute bottom-0 left-0 -translate-x-full ease-out duration-500 transition-all translate-y-full mb-9 ml-9 group-hover:ml-0 group-hover:mb-32 group-hover:translate-x-0"></span>
      <span className="relative w-full text-left text-gray-900 transition-colors duration-300 ease-in-out group-hover:text-green-400">
        Paste
      </span>

I want to ble able to use all buttons in every order


Solution

  • Modifying the input element directly doesn't change the value of the text variable that you declared with const [text, setText] = useState("Enter text here"). You need to call setText after reading the clipboard value:

    const inputToPaste = () => {
      navigator.clipboard.readText().then((inputX) => {
        setText(inputX);
      });
    };