Last active
September 8, 2017 06:46
-
-
Save alexkrolick/ac2e0725459553d40c3cac01a680d281 to your computer and use it in GitHub Desktop.
Renderless 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
/* Edit on Codepen: https://codepen.io/alexkrolick/pen/QMXMMv */ | |
class StateContainer extends React.Component { | |
constructor(props) { | |
super(props); | |
} | |
get handlers() { | |
return {}; | |
} | |
render() { | |
return null; | |
} | |
} | |
function combine(Container, Presenter) { | |
if (!Presenter) return combine.bind(undefined, Container); | |
class Combined extends Container { | |
constructor(props) { | |
super(props); | |
} | |
render() { | |
return Presenter( | |
{ ...this.props, ...this.state, ...this.handlers }, | |
...this.context | |
); | |
} | |
} | |
Combined.displayName = `${Container.name}(${Presenter.name})`; | |
return Combined; | |
} | |
class A extends StateContainer { | |
constructor(props) { | |
super(props); | |
this.state = { text: "foo" }; | |
} | |
get handlers() { | |
return { | |
setText: e => this.setState({ text: e.target.value }) | |
}; | |
} | |
} | |
const B = ({ text, setText }) => <input onChange={setText} value={text} />; | |
const C = combine(A)(B); | |
ReactDOM.render(<C />, document.querySelector(".app")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment