Home > Back-end >  How Can I Change Next.Js Image Component src with animation?
How Can I Change Next.Js Image Component src with animation?

Time:06-23

In Nextjs, I can change the src using state when I hover over the image, but I want to do this with animation like fadein, fadeout.

const [logoSrc, setLogoSrc] = useState("/logo.png");
<Image
   src={logoSrc}
   width={237}
   height={64}
   priority
   onm ouseEnter={() => {
      setLogoSrc("/hover-logo.png");
    }}
      onm ouseOut={() => {
      setLogoSrc("/logo.png");
    }}
/>

CodePudding user response:

An image's src propriety is sadly not part of animatable properties. If you want an animation you could load the two images, hide and show them trough CSS, something like this:

body {
  margin: 0;
}
.img-container {
  position: relative;
  height: 100vh;
}

.img-container .img2 {
  opacity: 0;
  transition: 1s;
}

.img-container:hover .img2 {
  opacity: 1;
}

.img-container img {
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div >
  <img  src="https://images.unsplash.com/photo-1648737966174-c5ef7b893fcd?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw=&auto=format&fit=crop&w=500&q=60" />
  <img  src="https://images.unsplash.com/photo-1654175979772-0f0eaa672d08?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw4fHx8ZW58MHx8fHw=&auto=format&fit=crop&w=500&q=60" />
</div>

CodePudding user response:

You can add css styles to next/image component - see https://nextjs.org/docs/api-reference/next/image and search for "CSS styles".

And then you can use css3 transitions, good descriptions is here: CSS3 Transition - Fade out effect

Have fun :)

  • Related