Search code examples
reactjshovermouseeventmouseentermouseleave

In React, onMouseEnter or hover is not working as expected


I have one image with opacity = 1 at the beginning.

When mouse enters the image, change opacity = 0.5. When mouse leaves the image, change the opacity back.

here is one code:

mouseEnter() {
    console.log('mouse enter')
    const classname = '.' + this.props.post.code
    document.querySelector(classname).classList.add('image-hover-opacity')
}

mouseLeave() {
    console.log('mouse leave')
    const classname = '.' + this.props.post.code
    document.querySelector(classname).classList.remove('image-hover-opacity')
}

    render() {
        <img src={src} onMouseEnter={::this.mouseEnter} onMouseLeave={::this.mouseLeave} />
    }

onMouseEnter and onMouseLeave are fired when mouse enters and leaves the image, respectively, good. But the problem is when I move the mouse inside the image, both onMouseEnter and onMouseLeave are fired.

And I have tried css solution as well, when I hover on image, change the opacity property. But the problem is the same: when I move mouse inside the image, :hover and not hover are fired multiple times.

How to solve this? thanks


UPDATE There is something in my previous code. Created one jsfiddle, and it works. sorry guys


Solution

  • Using document.querySelector is not a very React way of thinking. You can try this approach:

    • Use a div wrapping this img to avoid this weird mouseEnter behavior
    • Use this.state with opacity

      constructor() {
        this.state = {
          opacity: 1
        }
      }
      
      mouseEnter() {
          console.log('mouse enter')
          this.setState({opacity: 0.5})
      }
      
      mouseLeave() {
          console.log('mouse leave')
          this.setState({opacity: 1})
      }
      
          render() {
            <div style={{opacity: this.state.opacity}}>
              <img src={src} onMouseEnter={::this.mouseEnter} onMouseLeave={::this.mouseLeave} />
            </div>
          }