The Impact of Using Multiple Images in Animation is Strikingly Dynamic

For my small personal project, I am using ReactJs and Tailwind to render a list of 6 images. Here is the code snippet:

import React from "react";
import Images from "../images";

export default function PictureHeader() {
    const [pictureIndex, setPictureIndex] = React.useState(0);

    const animationRef = React.useRef<HTMLDivElement>(null);
    const node = animationRef.current;

    const pictures: string[] = Images.pictures;

    const removeAnimation = () => {
        node?.className.includes("fade-out")
        ? node.className.replace("fade-out", "fade-in")
        : node?.className.concat(" fade-in");
    }

    React.useEffect(() => {
        removeAnimation();
        setInterval(() => {
        nextPicture();
    }, 2500);
    });

    const nextPicture = () => {
        const newIndex = (pictureIndex + 1) % pictures.length;
        setPictureIndex(newIndex);
        node?.className.replace("fade-in", "fade-out");
    }

    console.log(pictureIndex);

    return (
    <div className="padding-10 top-0 inset-x-0 place-content-center">
        <div className="w-4/5 select-none relative rounded-lg">
            <div ref={animationRef} className="absolute content-left aspect-w-16 aspect-h-9 cover z-0">
            <img src={pictures[pictureIndex]}  />
            </div>
            <div className="absolute inset-x-0 bottom-0 justify-items-center z-10">
            <h1 className="6xl font-dancing">
                Sierra and Adam
            </h1>
            <h2 className="4xl font-dancing">
                Save the date for a match of the Millenia!
            </h2>
            </div>
        </div>
    </div>
    );
}

However, when the page runs, the images are displayed in a strange pattern like this: 0,0,1,1,0,0,1,1,2,2,0,0,1,1,2,2,3,3... which could be unsettling for users. Is there something I am missing or doing wrong in my implementation? Any assistance would be greatly appreciated!

Answer №1

It seems that I made a silly mistake by forgetting to clear the interval:


    React.useEffect(() => {
        removeAnimation();
        const interval = setInterval(() => {
            nextPicture();
        }, 2500);
        return () => clearInterval(interval);
    });

I speculate that the reason for this oversight is due to the accumulation of intervals, causing the state to change rapidly and overflow the queue.

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

The insertion was unsuccessful: Technique used in Meteor 1.3 and React

I am looking to add some simple text to the MongoDB using React. However, when I submit the form, the following error message is displayed in the console: insert failed: Method '/resolutions/insert' not found My setup includes autopublish and i ...

The information is not being stored in Excel despite the fact that the Excel document has been generated with a header

I have been working on a project that involves fetching book details from the Google Books API and using generative AI to create descriptions for them. I have successfully created an Excel file, but I am facing an issue with saving data inside it. It' ...

Color of the border to be applied on only a

I've been experimenting with view's border style properties to achieve a dynamic partial coloring of a circular shape, but I'm having difficulty making it work. My goal is to create something like this: https://i.sstatic.net/Xb0l7.png http ...

Having trouble with dynamic Open Graph meta tags not appearing correctly in the Facebook debugger tool when using Next

After experimenting with various methods like utilizing the base "Head" feature of NextJs, react-helmet, and next-seo packages to include meta tags, I found that they function properly on the client side and can be seen in browser inspection tools. However ...

Utilize Datatables to apply filters dynamically

For displaying a list loaded via an AJAX call to the server, I utilized the datatables jQuery plugin. To integrate the search input inside my sidebar, I made use of the bFilter property to hide the filter. $(function () { var generatedCustomerTable = ...

Using React to map and filter nested arrays while also removing duplicates

Hello, I recently started working with react and I've encountered a challenge while trying to map an array. const fullMen = LocationMenuStore.menuItems['menu']['headings'].map((headings: any) => { <Typography>{ ...

Making sure that a footer div is consistently positioned at the bottom of the container div, regardless of the dimensions of the other elements

I am facing a challenge with a container div which has child elements. <div class='wrapper'> <div class='content'></div> <div class='footer'></div> </div> The height o ...

Creating unique backgrounds for multiple webpages with React (Ensuring backgrounds stay consistent after refreshing)

Home.js file const Home = () => { var navigate = useNavigate(); const changeBackground = () => { navigate("/builder"); var htmlElement = document.getElementsByTagName('html'); htmlElement[0].style.backgr ...

Implementing session timeout functionality in a ReactJS component

I need assistance with implementing session timeout on my login page. The goal is to display a session timeout alert a few seconds before the session expires, and then redirect the user back to the initial page once the session times out. Below is an excer ...

Using MSAL for secure authentication and authorization in React.js

I am new to React and currently working on implementing Single Sign On Authentication in my React App. Goals: Create a login page where users can enter their email address When the user clicks sign-in, display the SSO popup (using Azure AD) for acceptin ...

What could be causing an issue with CORS in ExpressJS in one scenario but not in another?

I am currently in the process of setting up a database and connecting it to various routes. Interestingly, I have been successful with one route ('register') but encountering issues with another ('login'). Whenever I attempt to run the ...

Tips for changing the tabindex of a dialog manually in MUI

I'm currently working on adjusting the tabindex of an MUI Dialog component. Upon inspecting the generated HTML for the Dialog, I noticed the following tag: <div class="MuiDialog-container MuiDialog-scrollPaper" role="none presentati ...

The use of `import { Provider as AuthProvider } from "next-auth/client"` is causing an issue within the `_app.js` file and

Currently, I am watching a video on authentication at the 39-minute mark: Watch Video. The authentication part is shown in _app.js. Upon trying to import { Provider as AuthProvider } from "next-auth/client", I encountered the following error mes ...

Responsive design is causing issues with the stacking of rows in Bootstrap

Currently in the process of creating a website using HTML5, CSS3, and Bootstrap technologies. Encountering difficulties while attempting to establish a stacked row-column layout. On desktop view, the design appears as desired, resembling this example: ht ...

The default expansion behavior of Google Material's ExpansionPanel for ReactJS is not working as expected

Currently, I am in the process of developing a ReactJS application that utilizes Google's Material-UI. Within this project, there is a child class that gets displayed within a Grid once a search has been submitted. Depending on the type of search con ...

Develop an innovative showcase page showcasing 151 individual profiles with React Router

I am new to using React Router and feeling a bit confused about how to proceed. On my homepage, I have 151 unique monster thumbnails. When a user clicks on a thumbnail, they should be directed to the specific monster's 'show page'. Currently ...

Aligning a grid container in the middle

#panelb { background: lightblue; display: grid; grid-template-columns: repeat(auto-fit, 300px); } .card { background: gold; } .imgcard { display: block; width: 100%; margin: 0 auto; } <div id='panelb'> <div class=' ...

Error 404 - CSS file missing: encountering a 404 error while attempting to execute Flask code

Hello there! I'm still getting the hang of programming, especially when it comes to web development. Recently, I encountered an issue with my CSS file - whenever I link it to my HTML and run the Python code, I get an error saying that the CSS file can ...

What could be causing jQuery animate to malfunction on mobile devices when a viewport is present?

Everything seems to be working fine on my desktop webpage, but when I try it on mobile, there is no scroll... $("HTML, BODY").animate({ scrollTop: 500 }, 1000); This post suggests that mobile devices may not scroll on the body, but on the vi ...

Encountering issues with the interaction between Bootstrap and my custom CSS file in a Flask app with

I am encountering an issue with my template where I have included both Bootstrap and CSS files, with Bootstrap loaded before CSS. However, when I try to apply custom CSS using IDs or classes, the changes do not reflect. Strangely, styling for h1 elements i ...