3

NOTE: I asked this question previously. Tolle you marked that question as a duplicate of this question. But it is different, in that in my case the ref is created this way:

ref={slider => (this.slider = slider)}

And in your proposed original question this way:

ref={this.stepInput}

The answer for your proposed original was to do it this way:

private sliderRef = createRef<Slider>();
// ...
<Slider {...settings} slide={classes.slide} ref={this.sliderRef}>

But then I can't do:

next = () => {
  this.sliderRef.slickNext();
};

because I get the error:

[ts] Property 'slickNext' does not exist on type 'RefObject<Slider>'.

With this being said, here is the question:

I'm building a React app using TypeScript. I'm using React-Slick's carousel.

I'm trying to programmatically change the slide of the carousel. Therefore I followed the documentation and tried to create a ref for the Slider.

<Slider ref={slider => (this.slider = slider)} {...settings}>

Now TypeScript complains that it does not know slider. So I tried declaring it like this:

slider: Slider | null;

If I try it like this, I get the error:

[ts] Property 'slider' has no initializer and is not definitely assigned in the constructor.

How is one supposed to make a ref work with TypeScript?

The only way I could find was to say:

slide: any;

which defeats the purpose of TypeScript .

J. Hesters
  • 13,117
  • 31
  • 133
  • 249
  • The reason I closed your other question as duplicate is because the accepted answer is a two-part answer where one of the solutions is the callback ref method you are using. Please read it more closely. – Tholle Nov 08 '18 at 08:59
  • @Tholle Oh wow, you were right. I'm so dumb, I'm sorry! – J. Hesters Nov 08 '18 at 09:05

0 Answers0