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};
    });
}}
2
  • 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) Commented Nov 8, 2019 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. Commented Nov 8, 2019 at 12:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.