Created
May 23, 2018 12:19
-
-
Save mittsh/8a2df4a65e1df839fd8b6f2df285496e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
const withHoverWatcher = WrappedComponent => { | |
return class extends Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
isMouseHover: false | |
} | |
this.elRef = null | |
this.mouseEnterListener = null | |
this.mouseLeaveListener = null | |
} | |
componentDidMount() { | |
setTimeout(() => { | |
if (!this.mouseEnterListener) { | |
this.mouseEnterListener = this.elRef.base.addEventListener('mouseenter', this.onMouseEnter.bind(this)) | |
} | |
if (!this.mouseLeaveListener) { | |
this.mouseLeaveListener = this.elRef.base.addEventListener('mouseleave', this.onMouseLeave.bind(this)) | |
} | |
}, 100) | |
} | |
componentWillUnmount() { | |
if (this.mouseEnterListener) { | |
this.elRef.base.removeEventListener(this.mouseEnterListener) | |
this.mouseEnterListener = null | |
} | |
if (this.mouseLeaveListener) { | |
this.elRef.base.removeEventListener(this.mouseLeaveListener) | |
this.mouseLeaveListener = null | |
} | |
} | |
didSetRefEl(el) { | |
// if moving from preact to React, instead use ReactDOM.findDOMNode(el) | |
this.elRef = el | |
} | |
onMouseEnter() { | |
const { isMouseHover } = this.state | |
if (!isMouseHover) { | |
const { handleChange } = this.props | |
if (handleChange) { | |
handleChange(true) | |
} | |
this.setState({ isMouseHover: true }) | |
} | |
} | |
onMouseLeave() { | |
const { isMouseHover } = this.state | |
if (isMouseHover) { | |
const { handleChange } = this.props | |
if (handleChange) { | |
handleChange(false) | |
} | |
this.setState({ isMouseHover: false }) | |
} | |
} | |
render() { | |
return <WrappedComponent isMouseHover={this.state.isMouseHover} | |
ref={this.didSetRefEl.bind(this)} | |
{...this.props} /> | |
} | |
} | |
} | |
export default withHoverWatcher |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment