Skip to content

Instantly share code, notes, and snippets.

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