Search code examples
javascriptreactjsjsxthisarrow-functions

Arrow functions and onChange


I was watching this react tutorial where the tutor passed an arrow function in onChange prop which in turn called the actual handler. This was done so that the this keyword will refer to the class where the handler was defined.But I dont understand the logic.I understand why we use bind and define the method as an arrow function to get the this keyword to point to the class which the method belongs tom .But i dont understand this one.Can please someone explain why it works

handler(e){

console.log(this.state.someVariable)
}
<input  type="text" onChange={(event)=>this.handler(event)}

Solution

  • If you understand scoping in JS you understand the this operator.

    Good reads:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

    https://medium.com/backticks-tildes/understanding-hoisting-and-scoping-in-javascript-39ea7b41e31