JamesL
JamesL

Reputation: 197

How do I change the value of a textarea with a `onCopy` while putting the value of the textarea into my copy buffer

I am currently trying to implement an onCopy handler in a textarea that changes the value of the textarea based on the onCopy event. As far as I can tell I am losing focus on my text area before the system's actual copy happens, meaning that I actually have no text selected when I am copying.

In the snippet below I am expecting "Copy the textbox" to appear in my copy buffer, instead, nothing happens. Neither the old value or the new value appear in my copy buffer.

My question isn't specifically about the copying the old value or the new value, either would be acceptable.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { text: 'Copy the textbox!' };
  }

  render() {
    return (
        <input
          type="textarea"
          value={this.state.text}
          onCopy={() => {
            this.setState({ text: 'Copied!' });
            return true;
          }}
          onChange={() => console.log("input.onChange")}
        />
    );
  }
}

ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Upvotes: 2

Views: 373

Answers (1)

devserkan
devserkan

Reputation: 17638

Do you accept solutions including setTimeout? :)

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { text: 'Copy the textbox!' };
  }

  render() {
    return (
        <input
          type="textarea"
          value={this.state.text}
          onCopy={() => setTimeout( () =>
            this.setState({ text: 'Copied!' }),
            100 )
          }
          onChange={() => console.log("input.onChange")}
        />
    );
  }
}

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

But, it is really weird that setting the value with setState prevents copying. At first, I thought setState is the problem here but if we set another random state property we can copy the old value.

Upvotes: 1

Related Questions