Search code examples
javascriptreactjsonmouseover

ReactJS - changing image onMouseOver does not work


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.


Solution

  • 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;