Infinite Image Animation

PHOTO EMBED

Sat Sep 14 2024 12:04:52 GMT+0000 (Coordinated Universal Time)

Saved by @asha #react

"use client";
import React, { useState, useEffect } from "react";

const ImageSlider = () => {
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [prevImageIndex, setPrevImageIndex] = useState(0);

  const images = [
    "https://via.placeholder.com/300x200.png?text=Image+1",
    "https://via.placeholder.com/300x200.png?text=Image+2",
    "https://via.placeholder.com/300x200.png?text=Image+3",
    "https://via.placeholder.com/300x200.png?text=Image+4",
  ];

  useEffect(() => {
    const intervalId = setInterval(() => {
      setPrevImageIndex(currentImageIndex);
      setCurrentImageIndex((prevIndex) => (prevIndex + 1) % images.length);
    }, 3000); // Change image every 3 seconds

    return () => clearInterval(intervalId);
  }, [currentImageIndex, images.length]);

  return (
    <div className="bg-base-100 relative max-h-[28rem] overflow-hidden rounded-t-[3.5rem] border-l-[12px] border-r-[12px] border-t-[12px] border-black/75 md:order-first md:aspect-[9/18] md:max-h-none md:max-w-[24rem] lg:rounded-[4rem] lg:border-[14px]">
      {images.map((image, index) => (
        <img
          key={index}
          alt={`Slide ${index + 1}`}
          fetchpriority={index === 0 ? "high" : "low"}
          className={`absolute inset-0 h-full w-full rounded-t-3xl  transition-all duration-1000 ease-in-out lg:rounded-3xl ${
            index === currentImageIndex
              ? "translate-x-0 opacity-100"
              : index === prevImageIndex
              ? "-translate-x-full opacity-0"
              : "translate-x-full opacity-0"
          }`}
          src={image}
        />
      ))}
    </div>
  );
};

export default ImageSlider;
content_copyCOPY

Image slider + automatic + animation