2

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
   onMouseEnter={() => {
      setLogoSrc("/hover-logo.png");
    }}
      onMouseOut={() => {
      setLogoSrc("/logo.png");
    }}
/>
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
Ali Altun
  • 23
  • 3

2 Answers2

2

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 class="img-container">
  <img class="img1" src="https://images.unsplash.com/photo-1648737966174-c5ef7b893fcd?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60" />
  <img class="img2" src="https://images.unsplash.com/photo-1654175979772-0f0eaa672d08?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw4fHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60" />
</div>
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
0

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 :)