How to automatically copy the text of an input?

Viewed 80

I am using react and I want that when a user clicks on an icon or button, a url is copied to the clipboard, but there is another text in the input or textarea ... let me explain:

I have this code (from another question on stackoverflow), but I want to go a bit further. Let's say that the code that appears in the textarea is not what I want to be copied to the clipboard, but rather a url that contains that code is copied. This is the code:

class CopyExample extends React.Component {

  constructor(props) {
    super(props);

    this.state = { copySuccess: '' }
  }

  copyToClipboard = (e) => {
    this.textArea.select();
    document.execCommand('copy');
  
    e.target.focus();
    this.setState({ copySuccess: 'Copied!' });
  };

  render() {
    return (
      <div>
        {
         document.queryCommandSupported('copy') &&
          <div>
            <button onClick={this.copyToClipboard}>Copy</button> 
            {this.state.copySuccess && '✓'}
          </div>
        }
        <form>
          <textarea
            ref={(textarea) => this.textArea = textarea}
            value='ABC123CD'
          />
        </form>
      </div>
    );
  }

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

But I want that instead of copying this code "ABC123CD", a url with that code is copied, something like this: "https://some-url/abc123cd/code"

1 Answers

You could manipulate the expected value before .select()

this.textArea.value = `https://some-url/${this.textArea.value}/code`;
this.textArea.select();

Demo codesandbox

Edit cocky-pasteur-s57zs

Related