0

I know this is Simple, but it is little confusing to me :(

Why the input value in the below case is not getting reset.

handleReset() {
  this.setState({ data: "" });
}

<button onClick={this.handleReset}>Reset</button>

However, when I use inline way in the onClick event, I'm able to reset the input value.

<button onClick={()=>{ this.setState({ data: "" });}}>Reset</button>

I created a working example using CodePen. Could anyone please guide me where I'm doing wrong.

coderpc
  • 4,119
  • 6
  • 51
  • 93

2 Answers2

3

You either need to bind the handleReset() function to the class or use an arrow function. The scope of this changes otherwise.

Try with an arrow function (which binds the scope):

handleReset = () => {
  this.setState({ data: "" });
}

5 more examples at: https://www.freecodecamp.org/news/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56/

UPDATE:

Small library that automatically binds methods to their class instances. https://www.npmjs.com/package/auto-bind

Grabofus
  • 1,924
  • 14
  • 17
1

Recommended approach

constructor(props) {
  super(props);
  this.handleReset = this.handleReset.bind(this);
}

handleReset() {
  this.setState({ data: "" });
}

<button onClick={this.handleReset}>Reset</button>
Gangadhar Gandi
  • 2,162
  • 12
  • 19