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");
    }}
/>

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

yes i used this method. It didn't turn out the way I wanted, but I guess that's how it should be.
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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.