Last active
April 29, 2018 06:10
-
-
Save cjkihl/abb2cb9dc585b6d53db8cd22162f565a to your computer and use it in GitHub Desktop.
HOC Example WithMouse
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
| // HOC that will add mouse position to Wrapped components props | |
| const WithMouse = WrappedComponent => | |
| class extends React.Component { | |
| constructor(props) { | |
| super(props); | |
| this.state = { mouseX: 0, mouseY: 0 }; | |
| } | |
| onMouseMove = e => { | |
| this.setState({ mouseX: e.clientX, mouseY: e.clientY }); | |
| }; | |
| componentDidMount() { | |
| window.addEventListener('mousemove', this.onMouseMove); | |
| } | |
| componentWillUnmount() { | |
| window.removeEventListener('mousemove', this.onMouseMove); | |
| } | |
| render() { | |
| return ( | |
| <WrappedComponent | |
| {...this.props} | |
| mouseX={this.state.mouseX} | |
| mouseY={this.state.mouseY} | |
| /> | |
| ); | |
| } | |
| }; | |
| // How to use the HOC WithMouse | |
| class MyComponent extends React.Component { | |
| render = () => ( | |
| <span> | |
| Mouse X: {this.state.mouseX} Mouse Y: {this.state.mouseY} | |
| </span> | |
| ); | |
| } | |
| export default WithMouse(MyComponent); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment