Having trouble with the onLoadingComplete props in the Next.js Image component?

Is there a way to properly retrieve the naturalWidth and naturalHeight using the onLoadingComplete props? I tried following the documentation on https://nextjs.org/docs/api-reference/next/image#onloadingcomplete but it doesn't seem to be working. Am I missing something?

This is my function:

const handleImageLoad = (e) => {
  console.log("load", e);
};

Then I am using the following component from next.js:

<Image
  onLoadingComplete={(e) => handleImageLoad(e)}
  className=""
  src={image["data_url"]}
  alt=""
  layout="fill"
  objectFit="contain"
/>

Even though I can see the console log when the image is loaded, I'm unable to extract the natural width and height. Any suggestions why the handleImageLoad function is not being triggered in this case?

onLoadingComplete={() => handleImageLoad()}

Answer №1

Edit: The issue has been resolved in version 11.1.3-canary.33


A noticeable issue is that the next/image component fails to trigger the onLoadingComplete handler when the provided src is a data URI. (It seems an issue has already been reported here regarding this.)

A temporary fix involves using Object URLs. It's possible to implement this workaround directly by following instructions from this discussion thread or related questions.

If you prefer to continue utilizing react-images-uploading, you can employ methods outlined in this forum post and others to convert the data URI to Object URL before passing it as the src for next/image. However, keep in mind this will result in a heavier performance load compared to handling the uploaded file manually.

Here is a practical demonstration: https://codesandbox.io/s/jolly-ellis-4htdl?file=/pages/index.js

Adding an alternative solution just for completeness:

import { useState } from "react";
import Image from "next/image";

const IndexPage = () => {
  const [src, setSrc] = useState("");

  const handleChange = (e) => {
    setSrc(URL.createObjectURL(e.target.files[0]));
    return true;
  };

  const handleImageLoad = (e) => {
    console.log("load", e);
  };

  return (
    <>
      <input
        type="file"
        id="foo"
        name="foo"
        accept="image/png, image/jpeg"
        onChange={handleChange}
      />
      <div
        style={{
          marginTop: "1rem",
          width: 600,
          height: 600,
          backgroundColor: "blue",
          position: "relative"
        }}
      >
        {src?.length > 0 && (
          <Image
            onLoadingComplete={(e) => {
              handleImageLoad(e);
            }}
            src={src}
            alt=""
            layout="fill"
            objectFit="contain"
          />
        )}
      </div>
    </>
  );
};

export default IndexPage;

Answer №2

I recently faced a similar issue where I wanted to display an image only after it had finished loading.

It appears that if you use display:none in the styling, the onLoadingComplete function will not trigger, like this:

<Image

    ...

    style={{
        display: "none"
    }}

    onLoadingComplete={(img) => { // this will not be invoked
        img.style.opacity = "block"
    }}
/>

To solve this problem, I had to implement a different styling approach and include an empty onError function (to ensure that onLoadingComplete is only called when the image source is valid and loaded):

<Image

    ...

    style={{
        visibility: "hidden",
        maxHeight: "0",
        maxWidth: "0"
    }}

    onLoadingComplete={(img) => {
        img.style.visibility = "visible"
        img.style.maxHeight = "none"
        img.style.maxWidth = "none"
    }}

    onError={() => {}}
/>

This solution was specifically tested with Next.js version 13.5.3

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

Whenever I make changes to a record in the MERN stack, the object ends up getting deleted

Every time I attempt to update a record, instead of updating the objects, they get deleted. Even though my routes seem correct and it's functioning fine in Postman. Routes: router.route('/update/:id').post(function (req, res) { Bet.findByI ...

React Hook useEffect is throwing an error due to missing dependencies: 'dispatch' and 'logout'. To resolve this, make sure to include them in the dependency array or remove the array altogether

I'm struggling to understand what the issue is with this code. It seems like I keep encountering this problem and haven't been able to fix it yet. const signOut = () => { dispatch({ type: "LOGOUT" }); dispatch({ type: & ...

What causes userAgent to be undefined within _app.tsx during the use of getInitialProps?

When I check the code below, I'm encountering userAgent being retrieved as undefined: const userAgent = context.req?.headers['user-agent'] ?? ''; The issue persists with isMobile, where it's also being returned as undefined a ...

Struggling to make Typescript recognize the css prop (emotion) when styling Material-UI components

I'm on a mission to set up a Typescript project with Material-UI v4.11.4 and implement emotion for styling in anticipation of the MUI v5 release. The aim is to integrate emotion into the project so developers can transition to using the new styling in ...

Successful Implementation of S3 and MongoDB File Upload feature in Next.js 14 Application

Currently, I am utilizing Aws-S3 to store files for a project. The main obstacle I am facing involves retrieving the object URL and incorporating it into the Mongoose data model as a string when calling the POST method. Below is the code snippet for Next. ...

Connect Datadog to NextJs using the app router

I am facing a challenge with integrating Datadog into my NextJs 14 app that uses the app router. In previous versions, I successfully integrated Datadog into React and NextJs apps without the app router by placing initialization code in the top level compo ...

How to eliminate the bottom border in Material UI TextField

Currently, I am utilizing Material UI in my project and this is the textField I am working with: text field reality As shown, there is a bottom border underline present. However, I am aiming to completely remove it. In the past, I would simply use `border ...

Input a new value into the registration field to update it

My current task involves adding a new text field to a React form using a button. I need this new input text field to be able to store data on a register. How can I go about setting this property? Typically, when creating a text field, you would utilize co ...

Date Range Selection Widget malfunctioning when used within a popup modal

Having trouble with integrating the rsuite daterangepicker and antd's daterangepicker into a React Material UI Dialog/Modal. The date picker popup seems to either not show up or appear outside of the modal window. Take a look at the image below: Clic ...

When using middleware in Next JS, the manifest fails to load during redirection

I've successfully completed multiple pwa projects using Next JS in the past, but this time I'm facing an issue where my site.webmanifest file is not loading properly. Upon inspecting the site.webmanifest in the browser, I noticed that it's l ...

When utilizing getServerSideProps in Next.js for SSR, the graphql context may be found to be

I am encountering an issue with using getServerSideProps on my page: export const getServerSideProps: GetServerSideProps = async (ctx) => { const apolloClient = initializeApollo() await apolloClient.query({ query: UserQuery, variables: { id ...

What is the proper way to manage the refresh token on the client's end within a JWT system?

Curious about what exactly occurs on the client side when the refresh token expires. Is the user directed to a login page and remains logged in, or does the client side log them out automatically? My understanding is that the refresh token is saved in an ...

Learn how to default export React with withRouter, all while taking advantage of Material UI's makeStyles

I have been working on integrating Material UI makeStyles with class components, passing useStyles as props while default exporting it in an arrow function. export default () => { const classes = useStyles(); return ( <LoginClass classes={cl ...

"Encountering an issue with Next.js where the Redux

Hey there, I'm working on a simple project using Nextjs. I need to access the state of my Redux store but I'm encountering an error when trying to use store.getState, it's throwing an error saying getState is undefined. Additionally, I have ...

Arrays contain multiple elements, not just a single item

Is it possible to display multiple objects in one container? For instance, I have an array let array = [1, 2, 3, 4, 5, 6, 7, 8, 9]; array.forEach((item, index) => ( <div> <div> item 1, 2, 3 </div> <div> item 4, 5, 6 </div ...

Avoiding Access-Control-Allow-Origin cors issue when integrating with Stripe

Currently, I am working on setting up a payment system using Stripe. Below is the post request code I am using with Express: try { const session = await stripe.checkout.sessions.create({ line_items: [ { price: `${priceId}`, // M ...

Using a React component with Material-UI style classes in TypeScript is not possible

Recently delving into react, I've embarked on a learning project utilizing typescript 3.7.2 alongside material-ui 4.11.0 and react 16.13.1. Initially, I structured my page layouts using functional components, but upon attempting to switch them to clas ...

What are the steps to properly set up an external image loader in next.js?

I'm currently leveraging next.js export to generate a static html export that is housed on google cloud storage. To achieve this, I have incorporated a workaround in my next.js configuration file. images: { loader: 'imgix', path: 'ht ...

Issue with Dismissing Material UI Snackbar

Having trouble dismissing the snackbar by clicking away or on the "X" button. It's supposed to disappear after 10 seconds but it just stays there! Not sure what I'm doing wrong. const Footer = () => { const [snackbarState, setSnackbarState] = ...

What is the process of deselecting a RadioButton?

Imagine I have a group of RadioButtons. After clicking one, I realize that I don't want to submit the form after all. Instead, I just want to cancel and return to the state where none are selected. How can I achieve this? ...