Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Forked from MoOx/Hoverable.js
Created September 11, 2018 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shelob9/87e9f98e5518d61a9405fd3cc746892d to your computer and use it in GitHub Desktop.
Save Shelob9/87e9f98e5518d61a9405fd3cc746892d to your computer and use it in GitHub Desktop.
Hoverable HoC for React components
// @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