DEV Community

Cover image for How to change the image on hover using JSX.
Kriyanshi Shah
Kriyanshi Shah

Posted on

How to change the image on hover using JSX.

I came across this problem while working for the display part of the e-commerce type project. So I thought it to share it with everyone.

Pre-requisite: React and JavaScript Basics.

When you want to change the image on hover and you want to do that by doing some change in JSX. Good news - You can do it!!

So here the simple logic is to use the onMouseOver and onMouseLeave events and change the src of the image in the JSX on the event of onMouseOver on the card. And change the src back to the original on the event on onMouseOut.

<div className="card">
    <img  src="https://image.ibb.co/b8UJBc/administration_architecture_big_ben_221166.jpg"
        onMouseOver={(e) => (
            e.currentTarget.src = "https://image.ibb.co/mmyvrc/anniversary_balloons_birthday_68369.jpg"
            )}
        onMouseLeave={(e) => (
            e.currentTarget.src = "https://image.ibb.co/b8UJBc/administration_architecture_big_ben_221166.jpg"
            )}
    />
</div>
Enter fullscreen mode Exit fullscreen mode

Here is the codepen link for the same:

Here,

  • onMouseOver - This event occurs when the mouse pointer enters an element.
  • onMouseOut - This event occurs when the mouse pointer moves out from the element.

Using this simple logic we can eliminate writing common CSS.
And, this is also helpful if the image is coming from backend.

I hope you enjoyed reading this article.

Happy learning.✨

Top comments (0)