0

Hi I am trying to copy a text that is outputted from the following code .

<Text style={{color: 'white', textAlign: 'center'}}>
        {rideDuration != '' ? rideDuration + 's' : null}
      </Text>

The setAmountDuration is defined in the following .

  const calculateAmountDuration = async () => {
    const duration = ride.stop.- ride.start
    let durationSec = duration/1000;
    setrideDuration(durationSec)
  }

I want to copy to clip-board the output 0.08s

The screenshot is given below Screenshot

1 Answers1

1

You can use this package to copy text to the clipboard.

npm i copy-to-clipboard --save

You can create a button or simply copy the text to clipboard as shown inside the function calculateAmountDuration()

import copy from 'copy-to-clipboard';

function Exmaple {

  let [rideDuration, setrideDuration] = useState('');

  const calculateAmountDuration = async () => {
    const duration = ride.stop.- ride.start
    let durationSec = duration/1000;
    setrideDuration(durationSec);
    
    // Copy to Clipboard the moment 
    // the ride duration ios calculated.
    copy(durationSec.toString());
  }
  
  // You can also have a button which copies to clipboard
  const handleCopyToClipboard = (event) => {
    event.preventDefault();
    copy(durationSec.toString());
  }
  
  return (
    <Text style={{color: 'white', textAlign: 'center'}}>
      {rideDuration != '' ? rideDuration + 's' : null}
    </Text>
    <button onClick={handleCopyToClipboard}>Copy!</button
  )
}
M. G.
  • 343
  • 1
  • 7
  • Hi, if i just wanted to copy he text rideDuration ,how can i do so?I dont want to use any button as such , just basic copying from the UI – Basic Visual Aug 12 '20 at 14:28
  • `copy(rideDuration);` Invoking this function will copy whatever you want to your clipboard. I have shown that is possible in this func -> `calculateAmountDuration` Just to be sure what is it exactly you are trying to achieve? Because this will only copy to the clipboard of the device as requested in the questoin. – M. G. Aug 12 '20 at 14:54
  • @MrigankaGhosh to copy some text to clipboard can be easily done in JS only so any package is not necessary for that. – Mayank Pandeyz Aug 12 '20 at 15:07
  • I am aware of that, but I wasn't sure if it works the same with components other an `input` element since you can't run the select method on them. It would have to be an input element and even in JS you would need a ref property to a component, then select it's content and then use document.execCommand('copy"). There are many packages which do that for us with ease. Hence I suggested an easy way out. – M. G. Aug 12 '20 at 15:54
  • I actually had the following error when i did the following `reselectPrevious(), reselectPrevious is undefined)` when i did the following `copy(durationSec.toString())` – Basic Visual Aug 12 '20 at 20:17