1

My goal is to create a stateless image button component that changes images when I hover over it and that I can later use in other places.

My current problem is that I can't set the "hover" image when the onMouseOver event is called. The image is not being displayed and it looks like this:

enter image description here

// Assets
import image from '../assets/normal.png';
import imageSelected from '../assets/selected.png';

const HoverImage = () => {
  function over(e) {
    e.currentTarget.src = { imageSelected };
  }
  function out(e) {
    e.currentTarget.src = { image };
  }
  return <img src={image} onMouseOver={over} onMouseOut={out} />;
};

export default HoverImage;

When I don't hover over the component the image is displayed correctly. What am I doing wrong or how can I improve the code to reach my goal?

Also what I don't want is to have the paths to the images hardcoded in e.g CSS. The best thing would be to set the images via props I guess.

L3M0L
  • 429
  • 8
  • 23

1 Answers1

4

Just Remove {} around imageSelected and image, when you insert {} around these actually you pass object, not your image.

import image from '../assets/normal.png';
import imageSelected from '../assets/selected.png';

const HoverImage = () => {
  function over(e) {
    e.currentTarget.src =  imageSelected ;
 }
  function out(e) {
    e.currentTarget.src =  image ;
  }
    return <img src={image} onMouseOver={over} onMouseOut={out} />;
   };

 export default HoverImage;

for your second question you can pass images as props and show them like this :

 const HoverImage = props => {
 function over(e) {
  e.currentTarget.src = props.hoverImage;
}
 function out(e) {
   e.currentTarget.src = props.normalImage;
}
return <img src={props.normalImage} onMouseOver={over} onMouseOut={out} />;
};

you can check this Sandboox for more information;

MBehtemam
  • 7,865
  • 15
  • 66
  • 108
  • I'd like to leave my demo here as well. I would use `onMouseEnter` & `onMouseLeave` as it makes toggling easier. https://codesandbox.io/s/63mv86l1w And in this [SO question](https://stackoverflow.com/questions/29981236/how-do-you-hover-in-reactjs-onmouseleave-not-registered-during-fast-hover-ove) there are more ideas how you could implement the hovering. – AWolf Dec 30 '18 at 15:55