4

I was working on a react.js app and I initially used the arrow function which worked, but then just out of curiosity I decided to try the normal function and the normal function didn't work. I think that they both should output the same thing, what is going wrong?

handleChange = event => this.setState({init: event.target.value})

handleChange(event){
  this.setState({init: event.target.value})
}
deBhailis
  • 75
  • 2
  • 3
  • check the es version you are using.According to that you should use the syntax.If the necessary module missing it will gives and error – Thusila Bandara Aug 10 '18 at 03:29

1 Answers1

16

Arrow functions and normal function are not equivalent.

Here is the difference:

  1. Arrow function do not have their own binding of this, so your this.setState refer to the YourClass.setState.

  2. Using normal function, you need to bind it to the class to obtain Class's this reference. So when you call this.setState actually it refer to YourFunction.setState().

Sample Code

class FancyComponent extends Component {
    handleChange(event) {
        this.setState({ event }) // `this` is instance of handleChange
    }

    handleChange = (event) => {
        this.setState({ event }) // `this` is instance of FancyComponent
    }
}
I Putu Yoga Permana
  • 3,980
  • 29
  • 33