So I have next and previous button, and next button is working very well but the previous button does not.. Here is the code.
import React,{useEffect,useState,useRef} from "react";
function Slider() {
const colors = ["#0088FE", "#00C49F", "#FFBB28"];
const items = [
[1,2,3],
[1,2,3],
[1,2,3]
]
const [index, setIndex] = useState(0);
useEffect(() => {
setIndex((prevIndex) =>
prevIndex === items.length - 1 ? 0 : prevIndex 1
)
}, []);
const handlePrev = e => {
console.log(index)
setIndex((prevIndex) =>
prevIndex === items.length - 1 ? 0 : prevIndex - 1
)
}
const handleNext = e => {
console.log(index)
setIndex((prevIndex) =>
prevIndex === items.length - 1 ? 0 : prevIndex 1
)
}
return (
<div className="slideshow">
<div
className="slideshowSlider"
style={{ transform: `translate3d(${-index * 100}%, 0, 0)` }}
>
{items.map((backgroundColor, index) => (
<div
className="slide"
key={index}
style={{ backgroundColor:colors[index] }}
></div>
))}
</div>
<div className="next-prev">
<div className="prev" onClick={e => handlePrev(e)}> <ion-icon name="chevron-back-outline"></ion-icon> </div>
<div className="next" onClick={e => handleNext(e)}> <ion-icon name="chevron-forward-outline"></ion-icon> </div>
</div>
<div className="slideshowDots">
{items.map((_, idx) => (
<div
key={idx}
className={`slideshowDot${index === idx ? " active" : ""}`}
onClick={() => {
setIndex(idx);
}}
></div>
))}
</div>
</div>
);
}
export default Slider
So basically what I am talking about this is that when I am trying to click the next button..it doesn't skip any pages but when I tried to click the previous it doesn't work properly. You can try this in your vscode. This is the css
code
.slideshow {
margin: 0 auto;
overflow: hidden;
max-width: 500px;
}
.slideshowSlider {
white-space: nowrap;
transition: ease 1000ms;
}
.slide {
display: inline-block;
height: 400px;
width: 100%;
border-radius: 40px;
}
/* Buttons */
.next-prev {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 35px;
}
.next,.prev {
background: beige;
cursor: pointer;
}
.slideshowDots {
text-align: center;
}
.slideshowDot {
display: inline-block;
height: 20px;
width: 20px;
border-radius: 50%;
cursor: pointer;
margin: 15px 7px 0px;
background-color: #c4c4c4;
}
.slideshowDot.active {
background-color: #6a0dad;
}
I believe there is something logical issue with this code
const handlePrev = e => {
console.log(index)
setIndex((prevIndex) =>
prevIndex === items.length - 1 ? 0 : prevIndex - 1
)
}
I tried to do it with prevIndex - 1 since I think it might work but it is skipping the middle part of page.
Anyone can help me please thank you.
CodePudding user response:
Your prev logic is inverted, the conditional should compare to the first index, and if true, set it to the last index
setIndex((prevIndex) =>
prevIndex === 0 ? items.length - 1 : prevIndex - 1
);