Skip to content

Instantly share code, notes, and snippets.

@dfguo
Forked from sebmarkbage/Enhance.js
Last active December 12, 2015 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfguo/3184f5cbae5bd545b9e8 to your computer and use it in GitHub Desktop.
Save dfguo/3184f5cbae5bd545b9e8 to your computer and use it in GitHub Desktop.
Higher-order Components
import { Component } from "React";
export var Enhance = ComposedComponent => class extends Component {
constructor() {
this.state = { data: 'Hello' };
}
render() {
return <ComposedComponent {...this.props} data={this.state.data} />;
}
};
export class EnhancerContainer extends Component {
constructor() {
this.state = { data: 'hello' };
}
renderChildren: function () {
return React.Children.map(this.props.children, function (child) {
return React.addons.cloneWithProps(child, {
data: this.state.data
})
}.bind(this))
},
render() {
return (<div>
{this.renderChildren())}
</div>)
}
};
import { Enhance } from "./Enhance";
class MyComponent {
render() {
if (!this.data) return <div>Waiting...</div>;
return <div>{this.data}</div>;
}
}
export default Enhance(MyComponent); // Enhanced component
// vs
<EnhancerContainer>
<MyComponent />
</EnhancerContainer>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment