After deploying React with Gatsby, the sequential fade-in animation for the gallery is not functioning as expected

If you want to see the source code, it's available here: Source Code

And to view the deployed site, click on this link: Deployed Site

The goal I'm aiming for is quite simple and direct.

Initially, I used a query to load all the image files from the `images` folder:

const data = useStaticQuery(graphql`
    query {
      allFile(
        filter: {
          extension: { regex: "/(jpg)|(jpeg)|(png)/" }
          sourceInstanceName: { eq: "images" }
        }
      ) {
        edges {
          node {
            childImageSharp {
              fluid(maxWidth: 800, quality: 95) {
                aspectRatio
                src
                srcSet
                originalName
                srcWebp
                srcSetWebp
                sizes
              }
            }
          }
        }
      }
    }

Subsequently, there's a `gallery` component that arranges these images into three groups, allowing navigation between them using `project1`, `project2`, and `project3`.

const Gallery = ({ minWidth }) => {
  let refs = {}

  const allPics = Image().map(({ childImageSharp }, i) => {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    refs[i] = useRef(null)
    childImageSharp.index = i
    return childImageSharp
  })

  const firsload = allPics.slice(0, 5)
  const secload = allPics.slice(5, 10)
  const third = allPics.slice(10)

  const [imgs, setImgs] = useState(firsload)

  const thumbnails = imgs.map(img => img.fluid.srcSet.split(" ")[0])

  return (
    <>
      <ProjectsContainer>
        <Project
          onClick={() => {
            setImgs(firsload)
          }}
        >
          Project 1.
        </Project>
        <Project
          onClick={() => {
            setImgs(secload)
          }}
        >
          Project 2.
        </Project>
        <Project
          onClick={() => {
            setImgs(third)
          }}
        >
          Project 3.
        </Project>
      </ProjectsContainer>
      <Mansory gap={"0em"} minWidth={minWidth}>
        {imgs.map((img, i) => {
          return (
            <PicContainer key={img.index}>
              <Enlarger
                src={thumbnails[i]}
                enlargedSrc={img.fluid.src}
                index={img.index}
                orderIndex={i}
                onLoad={() => {
                  refs[img.index].current.toggleOpacity(1) <-- use ref to keep track of every Enlarger 
                }}
                ref={refs[img.index]}
              />
            </PicContainer>
          )
        })}
      </Mansory>
    </>
  )
}

Each `Enlarger` element rendered by the `Gallery` represents a zoom image component.

import Img from "react-image-enlarger"

class Enlarger extends React.Component {
  state = { zoomed: false, opacity: 0 } <--- initially every image's opacity is 0, then it shows up by being toggled opacity 1

  toggleOpacity = o => {
    this.setState({ opacity: o })
  }

  render() {
    const { index, orderIndex, src, enlargedSrc, onLoad } = this.props
    return (
      <div style={{ margin: "0.25rem" }} onLoad={onLoad}> <-- where we toggle the opacity when the element is onloaded
        <Img
          style={{
            opacity: this.state.opacity,
            transition: "opacity 0.5s cubic-bezier(0.25,0.46,0.45,0.94)",
            transitionDelay: `${orderIndex * 0.07}s`,
          }}
          zoomed={this.state.zoomed}
          src={src}
          enlargedSrc={enlargedSrc}
          onClick={() => {
            this.setState({ zoomed: true })
          }}
          onRequestClose={() => {
            this.setState({ zoomed: false })
          }}
        />
      </div>
    )
  }
}

I have specifically indicated in the code snippet where I implemented the sequential fade-in animation by utilizing `ref` to control each `Enlarger` element's `toggleOpacity` method.

This code functions perfectly on localhost, during development phase. Feel free to check out the codesandbox link above to observe it in action. However, the issue arises only after deployment of the page. When you visit the deployed version (Deployed Version), you may notice that upon initial loading of the page, some images are missing due to their opacity still being at 0. This occurs because the line `refs[img.index].current.toggleOpacity(1)` may not be triggered when the images are loaded. Strangely enough, during navigation between projects, the animation and opacity changes work flawlessly with no issues. Yet, upon page refresh, the problem resurfaces.

I've been grappling with this dilemma for days without success in identifying the root cause. Even though I utilized ZEIT Now for deploying the site, switching to Netlify did not eradicate the problem either.

Answer №1

The delay in loading images on your production site is not related to deployment issues. Please check the network calls for images in the browser to identify the cause of slow loading times.

Answer №2

Aside from what Kishore mentioned, it could be beneficial to delay running your query until after the page has completely loaded (perhaps in componentDidMount). By utilizing setState, you can prompt a re-render once the content is fully available.

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 footer is floating somewhere in the middle of the page, not at the bottom

Currently working on a webpage with the Twitter Bootstrap Framework. The footer is supposed to be at the bottom of each page with lots of content, but on one sub-page it's appearing in the middle instead: http://gyazo.com/45232ab25cdeb7705f9775a969051 ...

Pair up balls that have matching numbers

A software application was designed with the following features: It can create 4 balls on the screen, each containing a numerical value Users have the ability to input values for new circles to be generated Upon clicking a button, 4 new circles with num ...

Creating animations for canvas using the .stroke() method, all done without the need for additional

I've noticed this question has been asked many times (I did my research), but I'm struggling to figure out how to animate the .stroke() command on a canvas. I came across some examples, however, they all seem to rely on external libraries that ar ...

If the item with the specified name is not found in the list, display an image using Vue's v-if directive

<ul class="ulItems" v-for="item in listingItems" :key="item.channels"> <li class="liItems"> {{ item.itemName }} </li> </ul> I am looking to incorporate an image in situations where th ...

Loop through an array of elements in JavaScript and retrieve the element with the largest pixel size

I am facing a challenge with elements positioned absolutely on a web page. My goal is to iterate over these elements and identify the one with the highest top value. I attempted two different approaches: const elems = document.querySelectorAll('.ind ...

Unable to retrieve response token from form in a Next.js/React application utilizing Cloudflare Turnstile

As a beginner in Next.js/React, I'm currently working on creating a basic contact form with Cloudflare Turnstile integration. Prior to implementing Turnstile, the form functioned perfectly, submitting data to the API and sending emails without any iss ...

Display bootstrap modal hyperlink in web browser search bar

Utilizing bootstrap cards with href tags allows users to click on them and open bootstrap modals. I want users to be able to copy the modal's URL link for sharing purposes, but the issue is that when the modal is opened, the URL remains unchanged. How ...

Updating a calendar page in Rails 4 using AJAX technology

Currently, I am utilizing jQuery's datepicker functionality to display a calendar. The intended behavior is that upon clicking on a specific date, the page should generate relevant information (in this case, a table showcasing available seating) assoc ...

Placing elements in Chrome compared to IE

I'm currently attempting to position elements in two rows using mathematical calculations. One of the elements, thumb_container, is a div that is absolutely positioned. Within this container, I am dynamically loading and appending image thumbnails usi ...

Using a third-party React component within a web-based forms application

Is it possible to include a Material UI component (https://material-ui.com/getting-started/usage/) in a web forms application? Below is the code I currently have, but it is not displaying the Button component. I am working with an ASPX file and using UMD ...

Initial values in Material UI multi-select not appearing as expected

I recently started using MUI and encountered a problem with an editing form that displays values from a database in the Select component. Some values are shown, but others, even though they exist in the initial value array (verified by console log), are ra ...

Is there a way to format wrapped lines with indentation in an unordered list?

Is there a way to indent the wrapped lines of text in an unordered list? The current layout is not quite what I want, as shown in the first image below. Ideally, I would like it to look more like the second image. I attempted to use margin-left: 56px; and ...

Navigating and Displaying Views with React and Express

As a beginner in web development, I successfully completed a project using Node, Express, and EJS (for the frontend). Now, I am eager to tackle another project with React as my frontend. Despite watching numerous React + Express tutorials on YouTube, I not ...

Transferring information between an ASP web form page and an Angular2 application

Currently, I am working on a project that involves dealing with a legacy WebForms system. The system is gradually being updated to Angular 2, but the transition is happening incrementally. In order to effectively integrate information from the legacy sect ...

Unpredictable $watch behavior in Angular for both synchronous and asynchronous code

In my scenario, the value for a watched variable can be set in the current stack or loaded asynchronously (it is encapsulated code). Because of this, I cannot guarantee that the value was changed when the watch handler is called. Although I have reviewed ...

Using ReactJS and Hooks to update state after the .map() function

Trying to update the state using values from an array. Here is an example: const [state, setState] = useState({}); const test = [1, 2, 3]; test.map((item, i) => { setState({ ...state, [`item-${i}`]: item }); }); The current s ...

Implementing a color change for icons in React upon onClick event

export default function Post({post}) { const [like,setLike] = useState(post.like) const [islike,setIslike] = useState(false) const handler=()=>{ setLike(islike? like-1:like+1 ) setIslike(!islike) } return ( <> <div classNam ...

I am experiencing an issue where the data from Firebase is not being properly stored

I am encountering an issue with the following block of code: class PaintingPage extends Component { constructor(props){ super(props) this.state = { paintings: [] } this.database = this.database.bind(this); } database = () => { le ...

Every time I try to use AgGrid selectors, they consistently come back with null results, even though the

I currently have an ag grid in my application: <app-my-component> <ag-grid-angular [gridOptions]="gridOptions" (gridReady)="setGridReady()"> </ag-grid-angular> </app-my-component> When running Karma- ...

What is the best way to access a file within a project folder using JavaScript?

Currently, I am tackling a react project that involves dealing with a video file located in the public folder. In a specific scenario, I need to read this file and then send it over to the server as a file. I attempted the code snippet below but unfortunat ...