Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save cjkihl/e1f7240938bbfdf0ea4e36c93018830c to your computer and use it in GitHub Desktop.
React Mixin Example
// Simple mixin that listens to mouse events and
// sets the state everytime the mouse position changes
var MousePosMixin = {
getInitialState() {
return { 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);
}
};
// This component will now have mouseX and mouseY in the state
var MyComponent = React.createClass({
mixins: [MousePosMixin],
render() {
return (<span>Mouse X: {this.state.mouseX} Mouse Y: {this.state.mouseY}</span>);
}
});
ReactDOM.render(
<MyComponent />,
document.getElementById('container')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment