Created
April 29, 2018 07:01
-
-
Save cjkihl/a0e93954caf51cd75abe23d00e8ff36e to your computer and use it in GitHub Desktop.
React RenderProps Example
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