Barty
Barty

Reputation: 567

nextjs image loader that shows a color first then fades to image

While the image is loading, I want to show a color (black) and have that fade to the image once the image is loaded. Is there any good way to do this?

import Image from 'next/image'

const myLoader = ({ src, width, quality }) => {
  return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}

const MyImage = (props) => {
  return (
    <Image
      loader={myLoader}
      src="me.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

Upvotes: 0

Views: 2230

Answers (1)

stickyuser
stickyuser

Reputation: 2890

First add classes for opacity. And add a function for onLoadingComplete.

<Image
  loader={myLoader}
  src="me.png"
  alt="Picture of the author"
  width={500}
  height={500}
  className={`${
    heroHasLoaded ? "opacity-100" : "opacity-0"
  } transition-opacity duration-500`}
  onLoadingComplete={doFadeIn}
/>

Add the callback function.

const doFadeIn = () => {
  setHeroHasLoaded(true);
};

You also need to set the initial background color. I set this on a <div> that contains the image.

Note that if this image is going to be the Largest Contentful Paint, then also add priority to the <Image /> component. https://nextjs.org/docs/basic-features/image-optimization#priority

Upvotes: 2

Related Questions