Define callback ref TypeScript and react-slick library

Viewed 2263

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. My component is like this:

import React from 'react';
import Resur from './Resur'
const Slider = require("react-slick").default;

export interface Item {
title: string;
restur: Rest[];
}

export interface Rest {
name: string;
online: boolean;
}

interface AppRefs {
slider: any;
}

class Section extends React.Component<{ item: Item }> {
 private slider: any;

 constructor(props: any) {
    super(props);
    this.slider = null;
    this.setRef = element => {
        this.slider = element;
    };
}
renderArrows() {
  return (
    <div className="slider-arrow">
    <button
      className="arrow-btn prev"
      onClick={() => this.slider.slickPrev()}
    >
        <i className="fa fa-chevron-left"></i>
    </button>

    <button
      className="arrow-btn next"
      onClick={() => this.slider.slickNext()}
    >
        <i className="fa fa-chevron-right"></i>
    </button>
  </div>
);
};
render() {
const settings = {
  infinite: true,
  slidesToShow: 3
};
  var rests = this.props.item.restur.map(function(rest, index) {
    return (
      <Resur rest={rest} key={index} />
    )
  });
return(
  <div>
      <h4 className="section-title text-center">{this.props.item.title}</h4>
      <hr></hr>
      {this.renderArrows()}
      <Slider ref={this.setRef} {...settings}>
        {rests}
      </Slider>
  </div>
  )
 }
}
export default Section

When I defined the callback ref in my component like this, there is an error which says: "Property 'setRef' does not exist on type 'Section'". How can I define my callback ref in TypeScript for react-slick library?

1 Answers

To add properties to a typescript class, you need to define their types in the body of the class.

class Section extends React.Component<{ item: Item }> {
 private slider: typeof Slider | null; // <---- improved this type
 private setRef: (element: typeof Slider | null) => void; // <---- added this

 constructor(props) {
    super(props);
    this.slider = null;
    this.setRef = element => {
        this.slider = element;
    };
}
Related