1

i saw similar questions but can't get some solution.

i have some input when you paste some text to input i'm trying to set it to state and render this text. But when paste in first time state not change in second time when paste everything works.

I don't understand why it happen i already used some setTimeOut function too for it but not helped.

here is my code:

import React from "react";
import { render } from "react-dom";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      no: ""
    };
  }

  pasteSomeText = e => {
    this.setState({
      no: e.target.value
    });
  };

  render() {
    return (
      <div style={styles}>
        {this.state.no}
        <input onPaste={event => this.pasteSomeText(event)} />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

Here is codeSandBox example: https://codesandbox.io/s/1-react-hello-world-tvscf?fontsize=14

user3348410
  • 1,771
  • 6
  • 29
  • 64

4 Answers4

3

Basically the reason why you get empty state on firts onpaste call is that onpaste fires before the input's value is changed. So you get empty event.target.value and for all other calls you get previous value.

And if you still decide to keep going with onpaste you should keep in mind that you can get pasted value with event.clipboardData.getData('Text') but it can differ from what have been pasted in input because of different behavior of clipboardData for different input types.

https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types

So for work with clipboard data I will recommend to use DataTransfer module from https://www.npmjs.com/package/fbjs to get more consistant behavior in different systems and browsers.

layonez
  • 1,626
  • 1
  • 15
  • 20
3

To get the data from the event, use e.clipboardData.getData('text'). See https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event

e.target.value gives you the value for the text field before it updates with the paste data, so you can cancel/modify the paste if you want.

  pasteSomeText(e) {
    this.setState({
      no: e.clipboardData.getData('text')
    });
  };

Side note: with the call from the HTML, you don't need to use this arrow function (which uses more memory), see my example above

Juan Mendes
  • 80,964
  • 26
  • 138
  • 189
0

Is a diferente kind of event you will need to get the clipboard data from the event and set it to the state

const value = e.clipboardData.getData('text')
-1

use

onChange

instead of using

onPaste

Updated https://codesandbox.io/s/1-react-hello-world-h2jgv

Yahiya
  • 571
  • 2
  • 13