Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change image on hover in JSX

How do I change an image on hover in JSX

I'm trying something like this:

<img src={require('../../../common/assets/network-inactive.png')}
onMouseOver={this.src = require('../../../common/assets/network.png')}
onMouseOut={this.src = require('../../../common/assets/network-inactive.png')} />
like image 846
Shahaji Avatar asked Feb 09 '18 10:02

Shahaji


2 Answers

I will assume you are writing this code in a React component. Such as:

class Welcome extends React.Component {
  render() {
    return (
       <img src={require('../../../common/assets/network-inactive.png')}
       onMouseOver={this.src = require('../../../common/assets/network.png')}
       onMouseOut={this.src = require('../../../common/assets/network-inactive.png')} 
       />
    );
  }
}

Targeting this.src will not work in this case as you are essentially looking for something named src in your class. For instance this.src could find something like this:

src = () => (alert("a source"))

But that is not what you want to do. You want to target the image itself.

Therfore you need to enter the <img /> context. You can do that easily like this:

 <img
    onMouseOver={e => console.log(e)}
  />

From there you can target the currentTarget property, among others. This will enter the context of your element. So now you can do something like this:

  <img
    src="img1"
    onMouseOver={e => (e.currentTarget.src = "img2")}
  />

The same can be done for onMouseOut.

You can use this same method on your other elements, as you will certainly need to do this again. But be careful as this is a not the only solution. On bigger projects you may want to consider using a store (Redux), and passing props rather than mutating elements.

like image 87
typekev Avatar answered Sep 20 '22 20:09

typekev


Best is to manage this in the state:

class App extends Component {
  state = {
    img: "https://i.vimeocdn.com/portrait/58832_300x300"
  }

  render() {
    return (
      <div style={styles}>
        <img
          src={this.state.img}
          onMouseEnter={() => {
            this.setState({
              img: "http://www.toptipsclub.com/Images/page-img/keep-calm-and-prepare-for-a-test.png"
            })
          }}

          onMouseOut={() => {
            this.setState({
              img: "https://i.vimeocdn.com/portrait/58832_300x300"
            })
          }}
        />
      </div>
    )
  }
};

https://codesandbox.io/s/5437qm907l

like image 37
max li Avatar answered Sep 23 '22 20:09

max li