It is possible to switch between more already loaded images with React Spring?

  image, javascript, next.js, react-spring, reactjs

I want to switch between four images in index page. Now what I have is only change of source of image, that causes switch between images with transition. But problem is that when user loads page for the first time, new switched images needs to be load and that makes lets say gap between transitions, because new image isnt visible until load. Is there any way to only switch between already loaded images?

This is what I have now:

import {animated, config, useTransition} from "react-spring";
import Image from "next/image";
import {useEffect, useState} from "react";


const SliderImage = () => {

    const [index, setIndex] = useState(0);

    const images = [
        {id: 0, url: "/images/slide1.jpg", alt: "Chiptuning", priority: true},
        {id: 1, url: "/images/slide4.jpg", alt: "Autočalounictví", priority: false},
        {id: 3, url: "/images/slide2.jpg", alt: "Klimatizace", priority: false},
        {id: 4, url: "/images/slide3.jpg", alt: "Renovace světel", priority: false},
    ]

    const imageTransitions = useTransition(images[index], {
        from: { opacity: 0},
        enter: { opacity: 1},
        leave: { opacity: 0},
        config: config.molasses,
        key: images[index].id,
    });

    useEffect(() => {
        const slideInterval = setInterval(() => {
            setIndex((state) => (state + 1) % 4);
        }, 4000);

        return () => clearInterval(slideInterval);

    }, []);


   return imageTransitions((props, item) => (
        <animated.div style={props}>
            <Image
                src={item.url}
                alt={item.alt}
                layout="fill"
                objectFit="cover"
                priority={item.priority}
            />
        </animated.div>
    ))
}

export default SliderImage;

And what I want to do is have multiple images and only toggle between them.

 <animated.div style={props}>
            <Image
                ...
            />
 </animated.div>

 <animated.div style={props}>
            <Image
               ...
            />
  </animated.div>

 <animated.div style={props}>
            <Image
                ...
            />
 </animated.div>

 <animated.div style={props}>
            <Image
               ..
            />
 </animated.div>

Thank you for your help!

Source: Ask Javascript Questions

LEAVE A COMMENT