MoeSattler
MoeSattler

Reputation: 6904

How to trigger a state change when hovering over an element

I basically want to trigger a change in a components state when the user is hovering with his mouse over that component.

Since onMouseEnter and onMouseLeave are not properly working under certain conditions (https://github.com/facebook/react/issues/6807), is there any alternative?

EDIT: I think it has something to do with rerendering. When the components are of the same type, but I force a rerender, it causes the same issues.

class onHover extends Component {

  constructor(props) {
    super(props);
    this.state = {
      bool: false,
    }
  }

  render() {
    return (
      <div onMouseEnter={() => this.setState({ bool: true })} onMouseLeave={() => this.setState({ bool: false })}>
        {
          this.state.bool ? (
            <div key={Math.random()}>[OPTION1] show after onMouseEnter</div>
          ) : (
            <div key={Math.random()}>[OPTION2] show after onMouseLeave</div>
          )
        }
      </div>
    )
  }
}

Upvotes: 9

Views: 24644

Answers (1)

VelikiiNehochuha
VelikiiNehochuha

Reputation: 4373

From the docs:

The onMouseEnter and onMouseLeave events propagate from the element being left to the one being entered instead of ordinary bubbling and do not have a capture phase.

Try to use onMouseOut, onMouseOver instead

<div onMouseOver={() => this.setState({ bool: true })} onMouseOut={() => this.setState({ bool: false })}>
  {
    this.state.bool ? (
      <span>[OPTION1] show after onMouseEnter</span>
    ) : (
      <div>[OPTION2] show after onMouseLeave</div>
    )
  }
</div>

Upvotes: 16

Related Questions