I am trying to make a slider for my card component. but the problem is I am not able to display them in a proper manner.
I tried setting the width of Carousel inner from 100% to 25% but That increases the number of pages in the carousel and shows blank pages when data from my API runs out.
I want to loop through the data from API and did not want any extra blank pages at the end of the carousel.
providing the link for codesandbox Here is the link
To make a loop, You can reset the active index to 0 again. Therefore the updateIndex function should be like,
const updateIndex = (newIndex) =>{
if (newIndex < 0 || newIndex >= React.Children.count(children)) {
newIndex = 0;
}
setActiveIndex(newIndex);
};
Carousel.js
import React, { useState } from "react";
import "./Carousel.css";
export const CarouselItem = ({ children, width }) => {
return (
<div className="carousel-item" style={{ width: width }}>
{children}
</div>
);
};
const Carousel = ({ children }) => {
const [activeIndex, setActiveIndex] = useState(0);
const updateIndex = (newIndex) => {
if (newIndex < 0 || newIndex >= React.Children.count(children)) {
newIndex = 0;
}
setActiveIndex(newIndex);
};
return (
<>
<div className="carousel">
<div
className="inner"
style={{ transform: `translateX(-${activeIndex * 100}%)` }}
>
{React.Children.map(children, (child, index) => {
return React.cloneElement(child, { width: "100%" });
})}
</div>
</div>
<div className="indicators">
<button
onClick={() => {
updateIndex(activeIndex - 1);
}}
>
Prev
</button>
{React.Children.map(children, (child, index) => {
return (
<button
onClick={() => {
updateIndex(index);
}}
></button>
);
})}
<button
onClick={() => {
updateIndex(activeIndex + 1);
}}
>
Next
</button>
</div>
</>
);
};
export default Carousel;