Created
April 30, 2018 02:24
-
-
Save cjkihl/d5fa08809abaef42922ffe2777e9e74f to your computer and use it in GitHub Desktop.
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
// Component with renderProps that will add mouse position to the compoent that uses it. | |
class Mouse 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 = () => this.props.children(this.state); | |
} | |
export default class MyComponent extends React.Component { | |
render = () => ( | |
<Mouse> | |
{({ mouseX, mouseY }) => ( | |
<span> | |
Mouse X: {mouseX} Mouse Y: {mouseY} | |
</span> | |
)} | |
</Mouse> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment