I'm trying to create a carousel in React, and build is working perfectly. I am passing a json array of 4 objects. And I expect the carousel to work as below.
show slides 1,2,3 - 2,3,4 - 3,4,1, - 4,1,2 and so on in a circular loop. But currently I see, 1,2,3 - 3,4 - 1 - Blank - 1,2,3. Not sure of where I'm going wrong.
Here is my slider code.
import { useState, useEffect, useRef } from "react";
const Slider = ({
sliderData,
autoScroll = true,
intervalTime = 3000,
visibleSlides = 3,
}: any) => {
const [currentIndex, setCurrentIndex] = useState(0);
const intervalRef = useRef<number | null>(null);
const slideWidth = 100 / visibleSlides;
const slideStyle = {
transform: `translateX(-${currentIndex * slideWidth}%)`,
transition: "transform 0.5s ease-in-out",
};
const next = () => {
setCurrentIndex((current) => (current + 1) % sliderData.length);
};
useEffect(() => {
if (autoScroll) {
intervalRef.current = setInterval(next, intervalTime);
}
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
}, [autoScroll, intervalTime]);
const endIndex = currentIndex + visibleSlides;
const visibleServices = [];
for (let i = currentIndex; i < endIndex; i++) {
visibleServices.push(sliderData[i % sliderData.length]);
}
return (
<section
aria-labelledby="services-heading"
className={`overflow-hidden relative max-w-screen-xl mx-auto `}
>
<h1 id="services-heading" className="sr-only">
Our Services
</h1>
<div className="flex " style={slideStyle}>
{visibleServices.map((service, index) => (
<article
key={index}
className="bg-white border [&:not(:first-child)]:ml-8 flex flex-col gap-4 pb-6 h-auto w-[490px]"
>
<h3 className="px-4 text-xl font-bold ">{service.name}</h3>
<p className=" px-4">{service.c_serviceDescription}</p>
</article>
))}
</div>
</section>
);
};
export default Slider;
Where am I going wrong? Here is my fully working fiddle. Here is my output image: