Created
January 11, 2016 11:15
-
-
Save catalin-enache/90ba954a3d8312fc516e to your computer and use it in GitHub Desktop.
ES6 class decoration - aka Higher-Order Components
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
import React from 'react'; | |
class MyComponent extends React.Component { | |
componentDidMount() { | |
console.log('MyComponent did mount - do specific stuff'); | |
} | |
render() { | |
return (<div>MyComponent</div>); | |
} | |
} | |
let Decorator = ComposedComponent => { | |
return class extends ComposedComponent { // instead of class extends React.Component | |
componentDidMount() { | |
super.componentDidMount(); // allow ComposedComponent perform its stuff | |
console.log('Decorator did mount - do decorator stuff'); | |
} | |
} | |
} | |
// decorate MyComponent with Decorator | |
MyComponent = Decorator(MyComponent); | |
let myComponent = new MyComponent(); | |
myComponent.componentDidMount(); // simulate React lifecycle | |
// prints: | |
// MyComponent did mount - do specific stuff | |
// Decorator did mount - do decorator stuff |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Seems really a nice an elegant way.
Any known downsides from using decorators with React.js?