Created
November 4, 2020 20:24
-
-
Save karol-majewski/dee1852381e087426df34523ae9151ae to your computer and use it in GitHub Desktop.
The simplest possible higher-order component in React
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
export function withHover<T>(WrappedComponent: React.ComponentType<T & Hoverable>): React.ComponentClass<T> { | |
return class extends React.Component<T> { | |
state = { | |
hover: false, | |
}; | |
onMouseEnter: React.MouseEventHandler = () => { | |
this.setState({ hover: true }); | |
}; | |
onMouseLeave: React.MouseEventHandler = () => { | |
this.setState({ hover: false }); | |
}; | |
render() { | |
return this.state.hover ? <WrappedComponent onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} {...this.props} /> : 2; | |
} | |
}; | |
} | |
interface Hoverable<T = Element> { | |
onMouseEnter: React.MouseEventHandler<T>; | |
onMouseLeave: React.MouseEventHandler<T>; | |
} | |
interface Props extends Hoverable<HTMLDivElement> {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment