Reputation: 53
I want to change the image on the left side in every 3 seconds. Is there any techniques to do it without using react image slider?
I have attached my code here. I have tried to do it using react hooks. I have stored the images inside an array. The images changes perfectly only for first 8-10 seconds.
import React, { useEffect, useState } from "react";
import bannerImg1 from "../../Assets/Images/bannerProduct1.png";
import bannerImg2 from "../../Assets/Images/bannerProduct2.png";
import { Row, Col, Container } from "react-bootstrap";
import { FaCaretRight, FaChevronLeft, FaChevronRight } from "react-icons/fa";
import "./BannerSlider.css";
const BannerSlider = () => {
const imageArray = [bannerImg1, bannerImg2];
let [count, setCount] = useState(0);
const [image, setImage] = useState(imageArray[count]);
useEffect(() => {
setImage(imageArray[count]);
}, [count]);
useEffect(() => {
setInterval(() => {
setCount(count + 1);
}, 3000);
}, []);
return (
<div className="bannerSlider">
<Container>
<div className="slider-wrapper">
<Row className="d-flex align-items-center">
<Col lg={6} className="banner-image">
<img src={image} className="w-100 img-fluid" alt="" />
</Col>
<Col lg={6} className="banner-text">
<h2>Where your imagination come true</h2>
<p>
{" "}
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo
porro neque odio, at aspernatur explicabo?{" "}
</p>
<button>
Explore More <FaCaretRight className="banner-button-icon" />{" "}
</button>
</Col>
</Row>
</div>
</Container>
</div>
);
};
Upvotes: 0
Views: 1755
Reputation: 202864
From what I can read of your code you've a few issues:
useEffect
doesn't clear any running timers when the component unmounts.count
state in the interval callback so it's not updating correctly.// move image array outside component so it's not a dependency
const imageArray = [bannerImg1, bannerImg2, bannerImg3];
const BannerSlider = () => {
const [count, setCount] = useState(0);
// Save timer ref and return cleanup function to clear it
useEffect(() => {
const timerId = setInterval(() => {
// Use a functional state update to correctly increment the count
setCount(count => count + 1);
}, 3000);
return () => clearInterval(timerId);
}, []);
// `image` is derived state from the image array and current count
// Take the count mod array length to get the correct computed index
const image = imageArray[count % imageArray.length];
return (
<div className="bannerSlider">
<Container>
<div className="slider-wrapper">
<Row className="d-flex align-items-center">
<Col lg={6} className="banner-image">
<img src={image} className="w-100 img-fluid" alt="" />
</Col>
<Col lg={6} className="banner-text">
<h2>Where your imagination come true</h2>
<p>
{" "}
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo
porro neque odio, at aspernatur explicabo?{" "}
</p>
<button>
Explore More <FaCaretRight className="banner-button-icon" />{" "}
</button>
</Col>
</Row>
</div>
</Container>
</div>
);
};
Upvotes: 2