0

I need to convert an arrow function into a function. This is due to a problem with Slick Slider, as it does not support properly arrow functions.

I have convert this:

beforeChange={(current, next) => this.setState({slideIndex: next})}

Into this:

beforeChange={function(current, next) {
  this.setState({slideIndex: next});
}}

But does not work. Already tried this solution:

beforeChange={function(current, next) {
    this.setState(function() {
        return {slideIndex: next};
    });
}}
JetLagFox
  • 240
  • 4
  • 10
  • 1
    because `this` scope is wrong. When using arrow function (`=>`) `this` remains, but when using `function(){}`, `this` has it's own scope, so `this.setState()` will not work, unless you bind the function with `...}.bind(this)` – Calvin Nunes Nov 08 '19 at 12:27
  • 1
    _"This is due to a problem with Slick Slider..."_ - No, IE and its missing support is the problem, not Slick Slider. – Andreas Nov 08 '19 at 12:28

1 Answers1

1

Use bind for passing the context to the function:

beforeChange={function(current, next) {
  this.setState({slideIndex: next});
}.bind(this)}

This will pass this to the function so that when referencing this inside the function will be the one passed through bind.

Arrow functions do this automatically, they pass the context of where they're being called to the function itself, so by removing the arrow function you removed the correct context.

Other functions that will allow you to manually pass the context are: apply, call and the aforementioned bind.

SrAxi
  • 19,787
  • 11
  • 46
  • 65