I'm trying to dynamically toggle the visibility of a button element based on mouse movement (i.e., {visibility: visible} when the mouse is moving, {visibility: hidden} when it stops moving). The button is showing with onMouseMove, but I'm struggling with where to start on the second part. Since React doesn't have an onMouseStop event, what's the best way to achieve this?
export default class Infographic extends Component {
constructor(props){
super(props);
this.state = {
mouseMoving: false,
};
this.setMouseMove = this.setMouseMove.bind(this);
}
setMouseMove(e) {
e.preventDefault();
this.setState({mouseMoving: true});
}
render() {
const scrollButtonStyle = {
visibility: this.state.mouseMoving ? 'visible': 'hidden',
};
return (
<div onMouseMove={e => this.setMouseMove(e)}>
<button style={scrollButtonStyle}>Back to top</button>
<h1>Lorem Ipsum</h1>
</div>
);
}
}
UPDATE
Per the suggestions below, I added the following IIFE block to the setMouseMove method (using arrow functions for scope access) and it works just as expected. Thanks for the help!
setMouseMove(e) {
e.preventDefault();
this.setState({mouseMoving: true});
let timeout;
(() => {
clearTimeout(timeout);
timeout = setTimeout(() => this.setState({mouseMoving:false}), 50);
})();
}