Last active
December 15, 2023 06:17
-
-
Save rizalibnu/560e1c5275d3ebf4521a72383b5ddeea to your computer and use it in GitHub Desktop.
React slick typescript workaround for issue changing slide works incorrect when infinite is false and initialSlide > 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as React from 'react'; | |
| import {default as SlickSlider} from 'react-slick'; | |
| interface Props extends React.ComponentProps<typeof SlickSlider> { | |
| ref?: React.MutableRefObject<SlickSlider | null>; | |
| } | |
| const Slider = (props: Props) => { | |
| const {initialSlide} = props; | |
| const fallbackSliderRef = React.useRef<SlickSlider | null>(null); | |
| const sliderRef = props.ref || fallbackSliderRef; | |
| const hasSetPosition = React.useRef<boolean>(false); | |
| /** | |
| * workaround for issue changing slide works incorrect when infinite is false and initialSlide > 1 | |
| * https://github.com/akiran/react-slick/issues/1946#issuecomment-768935762 | |
| */ | |
| React.useEffect(() => { | |
| if ( | |
| sliderRef.current && | |
| !hasSetPosition.current && | |
| typeof initialSlide === 'number' | |
| ) { | |
| sliderRef.current.slickGoTo(initialSlide); | |
| hasSetPosition.current = true; | |
| } | |
| // run on first render only | |
| // eslint-disable-next-line react-hooks/exhaustive-deps | |
| }, []); | |
| return <SlickSlider {...props} ref={sliderRef} />; | |
| }; | |
| export default React.memo(Slider); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment