0

I have a styled component as below. It is a google social login button imgGoogleLogin is a path loaded by webpack.

I want to change the src attribute to another src when it is on hover.

Is there any way to achieve this? Thanks a lot

const GoogleLoginButton = styled.img.attrs({
  src: imgGoogleLogin,
})`
  width: 190px;
  height: 45px;
  &:hover {
    cursor: pointer;
  }
`;
Kwinten
  • 195
  • 3
  • 10

2 Answers2

1

I wanted to achieve something similar but I found that styled components cannot explicitly do this. I had to do it this way, ie create two components one hidden and when the parent is hovered I unhide it and hide the other one. Seems hacky but better than using e.setAttribute I think.

const GoogleLoginButton = styled.img.attrs(
        props => ({'src': props.img})
    )`
    display: inline;
    width: 190px;
    height: 45px;
    &:hover {
        cursor: pointer;
    }
`;

const GoogleLoginButtonHover = styled.img.attrs(
        props => ({'src': props.img})
    )`
    display: none;
    width: 190px;
    height: 45px;
    &:hover {
        cursor: pointer;
    }
`;

const GoogleLoginButtonParent = styled.div`
    &:hover ${GoogleLoginButtonHover} {
        display: inline;
    }

    &:hover ${GoogleLoginButton} {
        display: none;
    }
`;

In your render you use it like this:

<GoogleLoginButtonParent>
    <GoogleLoginButton
        img = {props.img}
    />
    <GoogleLoginButtonHover
        img = {props.imgHover}
    />
</GoogleLoginButtonParent>
J.Ewa
  • 205
  • 3
  • 14
0

You can achieve this with pure CSS:

By replacing your img tag with a div and setting its CSS as follow:

div {
    background: url('to_first_image');
}
div:hover {
    background: url('to_second_image');
}

If you rather keep your img tag and use some JS:

onHover = (e) => {
  e.setAttribute('src', 'source_to_first_img');
}

onUnhover = (e) => {
  e.setAttribute('src', 'source_to_second_img');
}

Credit to this answer : https://stackoverflow.com/a/18032363/10449875