-
-
Save Shelob9/87e9f98e5518d61a9405fd3cc746892d to your computer and use it in GitHub Desktop.
Hoverable HoC for React components
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
// @flow | |
import React, { Component } from "react" | |
type Props = { | |
onMouseEnter?: Function | boolean, | |
onMouseLeave?: Function | boolean, | |
} | |
type State = { | |
hovered: boolean, | |
} | |
// @todo try a more complex type for ComposedComponent + return type | |
export default (ComposedComponent: Function) => { | |
class Hoverable extends Component<Props, State> { | |
props: Props; | |
state: State = { | |
hovered: false, | |
}; | |
handleMouseEnter: Function = (event: SyntheticEvent<>): void => { | |
this.setState({ hovered: true }) | |
if (typeof this.props.onMouseEnter === "function") { | |
this.props.onMouseEnter(event) | |
} | |
}; | |
handleMouseLeave: Function = (event: SyntheticEvent<>): void => { | |
this.setState({ hovered: false }) | |
if (typeof this.props.onMouseLeave === "function") { | |
this.props.onMouseLeave(event) | |
} | |
}; | |
render(): React$Element<any> { | |
return ( | |
<ComposedComponent | |
{ ...this.props } | |
{ ...this.state } | |
onMouseEnter={ this.handleMouseEnter } | |
onMouseLeave={ this.handleMouseLeave } | |
/> | |
) | |
} | |
} | |
return Hoverable | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment