Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a state change when hovering over an element

Tags:

reactjs

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>
    )
  }
}
like image 216
MoeSattler Avatar asked May 20 '16 09:05

MoeSattler


People also ask

How do you make a hover effect in React?

To show an element on hover in React: Set the onMouseOver and onMouseOut props on the element. Track whether the user is hovering over the element in a state variable. Conditionally render the other element based on the state variable.

How do you hover in JSX?

You can use: const styles = { myStyleClassName: { padding: '16px 0px 16px 0px', '& a': { textDecoration: 'none', color: '#0000ee', }, '& a:hover': { textDecoration: 'underline', }, }, myButtonClass: { '&:hover': { textDecoration: 'underline', }, }, };

How do you use onMouseOut in React?

The onMouseOver event in React occurs when the mouse pointer is moved onto an element (it can be a div, a button, an input, a textarea, etc). The event handler function will be fired and we can execute our logic there. The onMouseOut event in React occurs when the mouse pointer is moved out of an element.


1 Answers

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>
like image 134
VelikiiNehochuha Avatar answered Sep 19 '22 20:09

VelikiiNehochuha