Skip to content

Instantly share code, notes, and snippets.

@frostney
Created April 7, 2015 10:15
Show Gist options
  • Save frostney/c6e2cc1c541819b64c5b to your computer and use it in GitHub Desktop.
Save frostney/c6e2cc1c541819b64c5b to your computer and use it in GitHub Desktop.
React mixins with decorators
var ReactMixin = function(...mixins) {
return function(Component) {
mixins.forEach(function(mixin) {
Object.keys(mixin).forEach(function(methodName) {
const methodValue = mixin[methodName];
if (methodName === 'statics') {
Object.keys(mixin.statics).forEach(function(staticProp) {
const staticValue = mixin.statics[staticProp];
Component[staticProp] = staticValue;
});
} else {
Component.prototype[methodName] = methodValue;
}
});
});
};
};
// Babel >= 5.0.0 is required and must be set to include Stage 1 ES7 proposals
const Alerter = {
showAlert() {
alert('Hey there!');
}
};
@ReactMixin(Alerter)
class AlertMe extends React.Component {
render() {
return <button onClick={this.showAlert}>Click me</button>
}
}
// Assuming a container element exists
React.render(<AlertMe />, document.getElementById('container'));
// Multiple mixins and static methods are supported as well
const Alerter = {
showAlert() {
alert('Hey there!');
}
};
const Boom = {
statics: {
boom() {
alert('Boom');
}
}
};
@ReactMixin(Alerter, Boom)
class AlertMe extends React.Component {
render() {
return <button onClick={this.showAlert}>Click me</button>
}
}
AlertMe.boom();
// Assuming a container element exists
React.render(<AlertMe />, document.getElementById('container'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment