Ways to display spinner animations during image loading on Next.js?

Currently, I am attempting to implement a spinner display while images are loading on a Next.js website. To achieve this, I am utilizing the NextUI UI library.

My website features several cards, and my goal is to showcase a spinner during the image loading process. In my attempts, I have experimented with a React hook and ternary operator:

import Loader from '../components/Loader'
import spinner from '../public/images/spinner.svg'

const Item = ({ item }) => {

  const [isLoading, setIsLoading] = useState(false);
 
  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      const result = await {item};   
      setIsLoading(false);
    };
    fetchData();
  }, []);
  
  return (
    <Link href={`/item/${item.id}`}>
      <Card flat isHoverable isPressable css={{ mw: "400px", alignContent: 'center'}}>
        {isLoading ? (
          <Loader />
        ) : (
         <Card.Image src={item.pic} alt={item.id} layout='responsive' css={{ alignContent: 'center'}} placeholder='blur' blurDataURL='/../public/images/spinner.svg'/>
        )}

("Loader" has been correctly renamed from the UI library)

I've also experimented with using the blurDataUrl property provided by Next.js, but it doesn't seem to function as expected.

Answer №1

I found success with this approach: displaying a circular loader while the image is loading.

import {useState, useEffect} from 'react';
import Image from "next/image";
import { CircularProgress } from "@mui/material";
import { styled } from "@mui/system";

export default function ServiceImage(props: any) {  
  const { src, alt } = props.props;
  const [isImageLoaded, setIsImageLoaded] = useState(false);
  useEffect(()=> {
    setIsImageLoaded(false);
  }, [src, alt]);

  const StyledImage = styled(Image)(({ theme }) => ({
    objectFit: "cover",    
    objectPosition: "50% 50%",
    [theme.breakpoints.up("md")]: {
      objectFit: "contain",
    }
  }));

  return (
    <>
    <StyledImage src={src} alt={alt} fill onLoadingComplete={() => {
      setIsImageLoaded(true);
    }}
    sx={{
      opacity: isImageLoaded ? 1 : 0,
      transitionDuration: "500ms",
      transitionProperty: "opacity",
      transitionTimingFunction: "ease-out",
    }}
    />
    <CircularProgress size={80} thickness={3} sx={{ 
      position: "absolute", 
      top:"50%", 
      left: "50%", 
      transform: "translate(-50%, -50%) !important",
      opacity: !isImageLoaded ? 1 : 0,
      transitionDuration: "500ms",
      transitionProperty: "opacity",
      transitionTimingFunction: "ease-out",
  }} />
    </>
  );
}

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

Using Next.js: What is the process for dynamically registering the quill-blot-formatter to react-quill that has been imported on the client side rendering exclusively

Currently, I am dynamically importing the react-quill library on the client side only by setting ssr: false. My functional component is functioning properly, but I now want to integrate the quill-blot-formatter package into the modules section of my quill ...

Exploring React JS Subdomains

I have been developing a MERN application that needs to support dynamic subdomains for each company, like companyname.localhost. In order to make this work, I made an adjustment in my .env file with the line: DANGEROUSLY_DISABLE_HOST_CHECK=true After a us ...

Having difficulty showing an image in the navigation provided via useContext()

The image is successfully displaying in the Profile.js screen and other areas. However, when attempting to pass the image via useContext() to display in Navigation.js, it shows as src(unknown). What could be causing this issue? https://i.stack.imgur.com/w ...

Using HTML, CSS, and JavaScript, the main tab must include nested subtabs to enhance navigation and

When a user clicks on a tab, another tab should open within the main tab. Depending on the selection in the second tab, input fields should appear while others hide. Something similar to the nested tabs on expedia.com. I have experimented with the tab vie ...

The click event will not be triggered if the element is removed by my blur event

My dropdown list is dynamic, with clickable items that trigger actions when clicked. Upon focus, the list displays suggested items When blurred, the list clears its contents The issue arises when blur/focusout events are triggered, causing my element to ...

How can you modify the starting point of data in jQuery flot?

Currently using Flot to create a graph displaying clicks per minute within the first 60 minutes of short URLs generated at . The graph currently displays data from minute 0 to minute 59. My query is about adjusting the data to start at 1 and end at 59, wh ...

React Error: Unable to iterate over this.state.descriptions

Currently facing an issue while trying to resolve this error https://i.stack.imgur.com/BZ304.png The goal is to generate an automated form using the following function: let descriptionsForm = ( <form> {this.state.descriptions.map((d ...

Encountering an issue where rendering a component named Exercise within the ExerciseList component is not allowed

The ExerciseList component is designed to display all the exercises that can be edited or deleted from the list. It returns the Exercise Component or function for this purpose. If anyone could take a look and help identify any mistakes in my code, it would ...

The Next.js dynamic route in production is displaying a 403 error instead of the expected 404. What might be causing this issue?

Whenever I attempt to access https://site.con/categories/, I am greeted with a 403 Forbidden error. However, if I visit https://site.con/categories/sport, everything works perfectly fine, and all other routes function properly. What could potentially be ca ...

Using getJSON to return key/value pair from local host URL in JSFiddle - A step-by-step guide

After following a tutorial on building an API using Python, Flask, SQLite, and SQLAlchemy, I have successfully tested the connection by hitting the localhost address in my browser. Now, I am curious if it is possible to test this connection and see the des ...

Incorporating a classList.toggle into a snippet of code

button, p, h1, h2, h3, h4, h5, a{ /* Define specific elements to use "fantasy" font */ font-family: Tahoma; } #main_body{ margin: 0px auto; background-color: #dedede; } #top_body{ /* Remove margin for simplicity */ } #t ...

Find the JavaScript code that selects the previous value chosen

When working with a select in React, I am facing an issue where the console.log is returning the last value selected instead of the current one. For instance, if I select 4 followed by 3 and then 5, the code will display 1 (default value), then 4, and fin ...

What is the most efficient way to transfer form data from one JSP page to another?

I need to transfer information from one webpage (1.jsp) to another webpage (2.jsp). The data that needs to be transferred includes checkboxes, radio buttons, and drop downs. This data will be used in 2.jsp to generate the appropriate page. Is there a way ...

Choose a particular optgroup simultaneously using custom JavaScript

Check out this Fiddle for an example I am facing a situation where I have two different types of option groups with options. My challenge is to ensure validation between these two groups. How can I achieve this? Situation 1 If I select something from g ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

Tried to enroll the RCTBridgeModule category as RCTFileReaderModule

Trying to register the RCTBridgeModule class RCTFileReaderModule with the name 'FileReaderModule' failed because the name was already taken by the FileReaderModule class. This issue arises when attempting to launch an application on iOS using th ...

Upon clicking a table row, generate a div underneath containing mapped data

My dynamic table is currently being filled with rows based on an array, but I want to display more data in an expanded view when a button in a row is clicked. However, I'm facing challenges as it seems I can't have two table rows within the same ...

Tips for sending multiple JSON objects using the ajax() method

As of now, I have successfully implemented a $.getJSON() call to fetch a JSON string from a specific URL. Here is the simplified code that is currently functioning well: $.getJSON("myURL",function(data){ var receivedJSON = data; }); The retrieved JSO ...

Exploring the interaction between React Hooks and the lifecycle methods in React

As a beginner in the world of reactjs and react native, I have come across information about both the react hooks and react life cycle methods. I am aware that there used to be 7 lifecycle methods before react 16.3, but now only 6 remain. Can someone pro ...