Skip to content

Instantly share code, notes, and snippets.

@bbandydd
Created December 17, 2017 12:28
Show Gist options
  • Select an option

  • Save bbandydd/3d035bef1c67f1b8437d8b0d6ed75841 to your computer and use it in GitHub Desktop.

Select an option

Save bbandydd/3d035bef1c67f1b8437d8b0d6ed75841 to your computer and use it in GitHub Desktop.
React Higher-Order-Component withMouse
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