Skip to content

Instantly share code, notes, and snippets.

@malte-wessel
Last active October 6, 2016 16:58
Show Gist options
  • Save malte-wessel/f88ee699c7cacacc281aec887c7dfec3 to your computer and use it in GitHub Desktop.
Save malte-wessel/f88ee699c7cacacc281aec887c7dfec3 to your computer and use it in GitHub Desktop.
Melody with React/Inferno: createComponent
import { createClass } from 'react';
const receiveProps = props => ({
type: 'RECEIVE_PROPS',
payload: props
}};
export default function createComponent(template, reducer) {
const { template, componentWillReceiveProps, ...rest } = definition;
if (!template) throw new Error('Please provide a template.');
return createClass({
...rest,
getInitialState() {
const action = receiveProps(this.props);
return reducer(null, action);
},
dispatch(action) {
const nextState = reducer(this.state, action);
this.setState(nextState);
},
componentWillReceiveProps(nextProps) {
const action = receiveProps(this.props);
const nextState = reducer(this.state, action);
this.setState(nextState);
componentWillReceiveProps.call(this, nextProps);
},
render() {
return template(this.state);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment