Last active
October 6, 2016 16:58
-
-
Save malte-wessel/f88ee699c7cacacc281aec887c7dfec3 to your computer and use it in GitHub Desktop.
Melody with React/Inferno: createComponent
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 { 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