Search code examples
reactjstypescriptecmascript-5

ES5 this.method is not a function


I have a typescript 2 class that targets ES5. I'm getting the err in the subject line in the console when I run it. The switch statement works fine, but increment() and decrement() methods don't execute.

class MyClass extends React.Component{
  ...
  increment() {
    console.log('increment()')
    ...
  }
  decrement() {
    console.log('decrement()')
    ...
  }

  buttonClick(btn) {
    console.log(btn)
    switch (btn) {
        case "prev":
            console.log('switch prev')
            this.decrement();
            //this.decrement;
            break;
        default:
            console.log('switch next')
            this.increment();
            //this.increment; eliminates err but method still doesnt execute
            break;
    }
  }
}

Solution

  • Make sure you bind this to your functions so that the value of this will be what you expect when you call the functions:

    class MyClass extends React.Component{
      constructor() {
        super()
        this.increment = this.increment.bind(this)
        this.decrement = this.decrement.bind(this)
        this.buttonClick = this.buttonClick.bind(this)
      }
      increment() {
        console.log('increment()')
      }
      decrement() {
        console.log('decrement()')
      }
      buttonClick(btn) {
        // ...
      }
    }
    

    You can also use property initialized arrow functions if you prefer:

    class MyClass extends React.Component{
      increment = () => {
        console.log('increment()')
      }
      decrement = () => {
        console.log('decrement()')
      }
      buttonClick = (btn) => {
        // ...
      }
    }