Reputation: 1
I am trying to build a carousel in react. For some reason, the ${fadeIn ? styles.fade_in : ""} line in className for rendering the animation didn't work. Even though I set it to false when calling handelSlider, it still rendered the fade_in animation, resault the carousel automatically move to the third image
My though was using a container to wrap the picture, and put them in a parent div with flex set to 100% so I can conditianly change the position for each photo. Each time after rendering the transition animation, I remove the animation then swap the current and next piture so it reset for the next animation. However, for some reason, even though when the fadein state set to false, the fadein css prop was still added. So confused, please help `
const Slider = () => {
const bannerPics = [banner1, banner2, banner3];
const [fadeIn, setFadeIn] = useState(false);
const [prev, setPrev] = useState(0);
const [next, setNext] = useState(1);
const prevPic = <img src={bannerPics[prev]} alt="" />;
const nextPic = <img src={bannerPics[next]} alt="" />;
const handelSlider = () => {
setFadeIn(!fadeIn);
setFadeIn(!fadeIn);
setTimeout(() => {
console.log(fadeIn);
if (next === bannerPics.length - 1) setNext(0);
else {
setPrev(prev + 1);
setNext(next + 1);
}
}, 3000);
};
return (
<div>
<div className={styles.banner}>
<div
className={`${styles.pic_container} ${fadeIn ? styles.fade_in : ""}`}
>
{prevPic}
</div>
<div
className={`${styles.pic_container} ${fadeIn ? styles.fade_in : ""}`}
>
{nextPic}
</div>
</div>
<button onClick={handelSlider}>MOVE</button>
</div>
);
};
export default Slider;
`
Upvotes: 0
Views: 166
Reputation: 10994
I think you were going for something like this:
const handleSlider = () => {
if (fadeIn) return;
setFadeIn(true);
setTimeout(() => {
setPrev((i) => (i + 1) % bannerPics.length);
setNext((i) => (i + 1) % bannerPics.length);
setFadeIn(false);
}, 1000);
};
.pic-container {
opacity: 1;
transition: opacity 1s;
}
.fade-in {
opacity: 0;
}
It's probably more accurate to call that class / variable just fade
since it is controlling both fading in and out.
https://stackblitz.com/edit/react-ts-n6sug4?file=App.tsx
Upvotes: 0