-1

I am using a switch statement in my reactJs application in ES6 mode. I have this statement:

switch (hoera) {
        case 'one':
            return this.runThis();
            break;
        default:
}

runThis(something)
{
        ..
}

The chromeconsole-error is :

TypeError: this.runThis is not a function

So runThis is a method defined on my component. Seems to work outside of a switchstatement though.

bier hier
  • 20,970
  • 42
  • 97
  • 166
  • 1
    Why don't you add `console.log(this, this.runThis)` so you find what it _is_. – Michael Lorton Feb 23 '17 at 00:42
  • You need to provide more context. But I guess it's a duplicate of [Unable to access React instance (this) inside event handler](http://stackoverflow.com/q/29577977/218196) – Felix Kling Feb 23 '17 at 06:13

1 Answers1

1

'this' does not refer to your component instance inside of your function containing the switch statement.

you could inside the constructor add this.myFunction = this.myFunction.bind(this) where myFunction is the function containing the switch statement.

Here is a good article about more ways to handle this inside of react : https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.gdmm0mob8

And here is some documentation about bind : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Kevin Amiranoff
  • 13,440
  • 11
  • 59
  • 90
  • I actually think its not the `runThis` that needs to be bound, but the function that has the switch in it (which isn't shown). – Jo Peyper Feb 23 '17 at 01:06
  • *"Inside the switch statement this is loosing its binding to the class."* That part is wrong. – Felix Kling Feb 23 '17 at 06:13