I had some problems with customizing the library dots, so I'm creating one manually. I'm trying to get the current index of the carousel when the swipe event occurs. I tried the onSwipe props, but it just returns the swipe direction
My Slider component:
export function PromotionalCarousel({
infinite = false,
speed = 500,
slidesToShow,
slidesToScroll,
children,
showArrows = true,
dots = false
}: PropTypes) {
const sliderRef = useRef(null);
const [slide, setSlide] = useState(0)
const changeSlide = (index: number) => {
sliderRef.current.slickGoTo(index);
};
useEffect(() => {
changeSlide(slide)
}, [slide])
useEffect(() => {
if (sliderRef.current === 0) {
setSlide(0);
}
if (sliderRef.current === 1) {
setSlide(1);
}
if (sliderRef.current === 2) {
setSlide(2);
}
}, [sliderRef])
return (
<div className={styles['main-area']}>
<section className={styles['slide-container']}>
<Slider
ref={sliderRef}
dots={dots}
infinite={infinite}
speed={speed}
slidesToShow={slidesToShow}
slidesToScroll={slidesToScroll}
className={styles.slider}
arrows={showArrows}
onSwipe={(index) => setSlide(Number(index))}
>
{children.map((element, i) => {
return (
<div key={i} className={styles.image}>
{element}
</div>
);
})}
</Slider>
</section>
<div className={styles['buttons-area']}>
<button
type='button'
className={styles['button-carousel']}
style={{
backgroundColor: slide === 0 ? '#fa6c00' : '#8A9197',
opacity: slide === 0 ? '1' : '.3'
}}
onClick={() => setSlide(0)}
/>
<button
type='button'
className={styles['button-carousel']}
style={{
backgroundColor: slide === 1 ? '#fa6c00' : '#8A9197',
opacity: slide === 1 ? '1' : '.3'
}}
onClick={() => setSlide(1)}
/>
<button
type='button'
className={styles['button-carousel']}
style={{
backgroundColor: slide === 2 ? '#fa6c00' : '#8A9197',
opacity: slide === 2 ? '1' : '.3'
}}
onClick={() => setSlide(2)}
/>
</div>
</div>
);
}
How can I get the current index of the carousel by the swipe function?
react-slick
provides 2 methods that allow you to get slide index:
beforeChange: (current, next) => {}
afterChange: current => {}
The different between these 2 methods are:
beforeChange()
will be triggered before the slide is changed (in all cases of swiping, click prev/next buttons or go to specific slide). It has 2 arguments: current
is index of the starting point, and next
is index of the target slide (not always equal to current + 1
).afterChange()
will be triggered after the slide is changed so now current
is index of the target slide (equals to next
of the beforeChange()
)