Is there a way to incorporate a subtle fading effect when transitioning between images?

I find this continuously changing image every 5 seconds to be a bit overwhelming without any smooth transition. Is there a way I can implement a short fade effect like what is possible in CSS?

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

import aa from '../imgs/aa.JPG'
import aa2 from '../imgs/aa2.JPG'
import aa3 from '../imgs/aa3.JPG'
import aa4 from '../imgs/aa4.JPG'
import gg from '../imgs/gg.jpeg'
import gg2 from '../imgs/gg2.jpeg'
import gg3 from '../imgs/gg3.jpeg'
import gg4 from '../imgs/gg4.jpeg'


import './AnimatedGalery.css'

const images = [aa, aa2, aa3, aa4, gg, gg2, gg3, gg4];


export default function () {

    let [currentIndex, setCurrentIndex] = useState(0);

    useEffect(() => {
        const intervalId = setInterval(() => {
            if(currentIndex == images.length - 1) {
                setCurrentIndex(currentIndex = 0);
            } 
            else {
                 setCurrentIndex(currentIndex = currentIndex + 1);
            }
        }, 5000)
        
        return () => clearInterval(intervalId);
    }, [])

    return (
        <div>
            <img src={images[currentIndex]} />
        </div>
    )
}

Answer №1

Check out React Spring at this link

View a live demo showcasing what you're looking for by visiting: here

In essence, the useTransition hook from React Spring will trigger animations based on the changing data passed to it.

import { animated, useTransition } from "@react-spring/web";
import * as React from "react";

const imageUrls = [
  "image1url",
  "image2url",
  "image3url"
];

export default function App() {
  const [index, setIndex] = React.useState(0);
  const [imageUrl, setImageUrl] = React.useState(imageUrls[index]);
  React.useEffect(() => {
    const timeoutId = window.setTimeout(() => {
      setIndex((s) => {
        let newIndex = 0;
        if (s < imageUrls.length - 1) newIndex = s + 1;
        setImageUrl(imageUrls[newIndex]);
        return newIndex;
      });
    }, 2500);

    return () => clearTimeout(timeoutId);
  }, [index]);
  const transition = useTransition(imageUrl, {
    from: { opacity: 0, transform: "translateY(-1rem) scale(0.75)" },
    enter: { opacity: 1, transform: "translateY(-0rem) scale(1)" },
    leave: { opacity: 0, transform: "translateY(1rem) scale(1.25)" }
  });
  const fragment = transition((style, item) => (
    <animated.div style={{ ...style, position: "absolute" }}>
      <img
        src={item}
        alt=""
        style={{ width: 200, height: 200, objectFit: "cover" }}
      />
    </animated.div>
  ));
  return (
    <div
      style={{
        display: "flex",
        width: "100vw",
        height: "100vh",
        alignItems: "center",
        justifyContent: "center"
      }}
    >
      {fragment}
    </div>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the size of a div using absolute positioning

Can a div with absolute position be resized? I need this pink modal to maintain the same width as the input and resize accordingly. This modal will be utilized in a dropdown component, so it should resize along with the input. Moreover, is using absolute ...

Anyone have any (placeholder) fetch URL parameters that require some time to resolve?

Can anyone share any fetch URL parameters that result in a loading time of roughly 5 seconds or longer for the promise to resolve when using fetch(urlArgument);? I'm eager to experiment and learn more. ...

Creating dynamic elements in JavaScript and assigning them unique IDs

Hi there, I'm currently working on a project that requires generating dynamic divs with a textbox and delete button inside each one. The challenge I'm facing is figuring out how to assign a unique ID to each textbox element so that I can properly ...

iOS alert notification for navigator

How can I fix the issue with my alerts not working on my iOS project? I am using Ionic and AngularJS to develop my app. The problem I am facing is that when the alert pops up, the title shows as "index.html". This is how I call the alert: alert("aaa"); ...

Enhancing Single Cards with React and Material UI Card Expander

Currently, I am utilizing React along with Material UI to craft 3 expandable cards containing images. The setup is running smoothly as expected; the cards render and expand almost perfectly. However, there is one major issue: all the cards expand simultane ...

A vertical divider within an ion-item collection

Currently, I am using Ionic and HTML to implement a vertical line within an ion-item in an ion-list. The desired outcome is to have something similar to this (the colored line after 'all-day'): I attempted the following approach: <ion-list&g ...

Table Template in XSLT

I am attempting to retrieve information in a tabular format, but I'm running into issues. The data is displaying vertically rather than in the horizontal table format I desire using standard HTML table tags. Is there a way to achieve this? Am I overlo ...

Encountering a ReferenceError in Angular 4 due to d3 not being defined when importing in a module

I'm looking to incorporate these imports into my angular 4 app.module, rather than adding them directly to my index file. In app.module.ts -> import d3 from "d3"; console.log(d3) // Confirming successful import of D3 import nvd3 from "nvd3"; H ...

React Material-UI eliminates the 'content' property from the CSS pseudo-element

Creating a React MUI Box and styling it like this: <Box id='my-box' sx={{ '&::before': { content: 'Yay! ', backgroundColor: 'red' } }} >Life is beautiful</Box> However, duri ...

When attempting to import a module conditionally in Next.js using dynamic import, the server-side rendering (SSR)

I have a component that I am dynamically importing using the dynamic function from Next.js. I also want to download the bundle based on a flag that I set in my code (loadWirelessBundle flag in the code below). While it successfully downloads the bundle and ...

The attempt to decode the string from POST using json_decode failed due to a hang-up in

I'm currently learning about PHP, JSON, and JavaScript. I am facing an issue with using the json_decode function in PHP after receiving a JSON string from JavaScript. I am able to save the JSON string to a file without any problem, but when I try to ...

Exploring recursive tree structures with ReactJS

Seeking assistance with implementing a tree view using JSON data in ReactJS. I have most of the functionality working except for the expand and collapse buttons. Currently, clicking on a subtree node expands the entire tree. What I am trying to achieve i ...

Troubleshooting Website Navigation Bar and Layout with HTML, CSS, and Bootstrap5

I am facing a challenge with navbar positioning. My navbar items are missing after adding the image below. I have attempted to adjust the element positions but to no avail :( I also tried to create a fixed-top navbar, but it didn't work either :( I ...

After closing a window in GXT, the Element will be removed using RootPanel's get(String id) method

I am working on a GWT project with the GXT framework, and I have an embed tag in my project.html as shown below: <embed type="application/nptta" width=100% height=100% id="testId"></embed> There is a formPanel that will use RootPanel.get("tes ...

Finding elements in Vue.js and Nuxt.js without using querySelectorAll

Currently, my code includes: var images = Array.from(this.$refs["dynaContent"].querySelectorAll("img")); While this code functions properly on the webpage, there is an error log displayed in the terminal: ERROR [Vue warn]: Error in ne ...

"Trouble ensues when OrbitControls fail to function properly while loading a

I have a code snippet that displays a 3D file (obj, stl, 3mf) uploaded by the user using three.js OBJLoader, STLLoader, and 3MFLoader. Everything seems to be working fine, but I attempted to integrate OrbitControls so users can zoom in, zoom out, rotate, e ...

What is the best way to use a CSS class in my script specifically for specific screen sizes?

Utilizing bootstrap 4, my code is executing a for loop to generate eight divs with the class "item". To display five items per row, I am using the class "col-2". However, this results in six items being shown in a single row. Since I cannot include the o ...

Scrolling horizontally in ng-grid version 2.0.11

In my application, I am utilizing a ng-grid with auto height and width. The challenge arises when dynamically adding columns to the grid. If there are too many columns to display, instead of showing a horizontal scrollbar, the columns shrink in size and ap ...

Spinning html/css content using JavaScript

Greetings! I am currently working on a demo site using just HTML, CSS, and JavaScript. Typically, I would use Ruby and render partials to handle this issue, but I wanted to challenge myself with JavaScript practice. So far, I have created a code block that ...

I am attempting to create basic animations using css, but I'm having some trouble

Currently, I am attempting to add animation to a css div without including the top property in the original div style. I omitted it because I wanted to delay the animation, so I placed it within the @keyframes property. However, the element disappears afte ...