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>
)
}
}
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.
You can use: const styles = { myStyleClassName: { padding: '16px 0px 16px 0px', '& a': { textDecoration: 'none', color: '#0000ee', }, '& a:hover': { textDecoration: 'underline', }, }, myButtonClass: { '&:hover': { textDecoration: 'underline', }, }, };
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With