Skip to content

Instantly share code, notes, and snippets.

@cjkihl
Last active April 29, 2018 06:10
Show Gist options
  • Select an option

  • Save cjkihl/abb2cb9dc585b6d53db8cd22162f565a to your computer and use it in GitHub Desktop.

Select an option

Save cjkihl/abb2cb9dc585b6d53db8cd22162f565a to your computer and use it in GitHub Desktop.
HOC Example WithMouse
// 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