I'm currently using "typescript": "^3.7.5"
and "react-slick": "^0.25.2"
.
The problem I am facing is that I'm not able to use the auto play methods slickPlay
and slickPause
with the new useRef
hook and typescript.
Goal: To be able to pause auto play and resume auto play with a play/pause button. My play/pause button will be next to the pagination dots.
My Code:
import React, { useStateuseRef } from 'react';
const myComponent = () => {
const [autoPlayOn, setAutoPlayOn] = useState<boolean>(true);
const sliderRef = useRef<typeof Slider | null>(null);
<Slider
ref={sliderRef}
appendDots={(dots): JSX.Element => (
<MyButton
onClick={() => {
setAutoPlayOn(!autoPlayOn);
if (autoPlayOn) {
sliderRef.slickPlay();
} else {
sliderRef.slickPause();
}
}}
/>
)}
{...otherSettings}
>
}
The type error that I am getting is:
No overload matches this call.
Overload 1 of 2, '(props: Readonly<Settings>): Slider', gave the following error.
Type 'MutableRefObject<typeof Slider | null>' is not assignable to type 'string | ((instance: Slider | null) => void) | RefObject<Slider> | null | undefined'.
Type 'MutableRefObject<typeof Slider | null>' is not assignable to type 'RefObject<Slider>'.
Types of property 'current' are incompatible.
Type 'typeof Slider | null' is not assignable to type 'Slider | null'.
Type 'typeof Slider' is missing the following properties from type 'Slider': slickNext, slickPause, slickPlay, slickPrev, and 8 more.
Overload 2 of 2, '(props: Settings, context?: any): Slider', gave the following error.
Type 'MutableRefObject<typeof Slider | null>' is not assignable to type 'string | ((instance: Slider | null) => void) | RefObject<Slider> | null | undefined'.
Type 'MutableRefObject<typeof Slider | null>' is not assignable to type 'RefObject<Slider>'.
I'm also getting another error when clicking on the button:
TypeError: sliderRef.slickPlay is not a function
I'm attempting to call the slick methods slickPlay
and slickPause
, however I'm running into type errors. I've looked at the examples https://github.com/akiran/react-slick/blob/master/examples/AutoPlayMethods.js however I'm not able to achieve the desired result still.
It confuses me to use these methods for functional components instead of class-based components. Adding in the layer of typescript makes it that much more challenging.
Thank you in advance.
I'll address the second part first: when using useRef
, you have to refer to .current
to get the actual instance. So, your calls would look like:
sliderRef.current.slickPlay();
Now the first part. This one, I'm willing to believe that this could change depending on which version of Typescript/React/react-slick you're using, but for me, Typescript stops complaining if I just use:
const sliderRef = React.useRef<Slider>(null);