Created
December 17, 2017 12:28
-
-
Save bbandydd/3d035bef1c67f1b8437d8b0d6ed75841 to your computer and use it in GitHub Desktop.
React Higher-Order-Component 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
| import React, { Component } from 'react'; | |
| import PropTypes from 'prop-types'; | |
| const withMouse = (WrappedComponent) => { | |
| return class extends Component { | |
| state = { | |
| x: 0, | |
| y: 0, | |
| } | |
| onMouseMove = (e) => { | |
| this.setState({ | |
| x: e.clientX, | |
| y: e.clientY, | |
| }) | |
| } | |
| render() { | |
| return ( | |
| <div onMouseMove={this.onMouseMove}> | |
| <WrappedComponent {...this.props} mouse={this.state}/> | |
| </div> | |
| ) | |
| } | |
| } | |
| } | |
| @withMouse | |
| export default class Content extends Component { | |
| static propTypes = { | |
| mouse: PropTypes.object, | |
| } | |
| render() { | |
| const { mouse } = this.props; | |
| return ( | |
| <div className="content"> | |
| {`mouse position: (${mouse.x}, ${mouse.y})`} | |
| </div> | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment