Skip to content

Instantly share code, notes, and snippets.

@honewatson
Last active July 20, 2017 23:04
Show Gist options
  • Save honewatson/355da710216afa90c2daed6e44403325 to your computer and use it in GitHub Desktop.
Save honewatson/355da710216afa90c2daed6e44403325 to your computer and use it in GitHub Desktop.
Basic Hyperapp Style application for React
const copy = obj =>
JSON.parse(JSON.stringify(obj));
export const app (obj) => {
let state = copy(obj.state);
const actions = {};
Object.keys(obj.actions).forEach(action => {
const actionWrapper = (...params) => {
if(Array.isArray(params)) {
params = copy(params);
}
const result = obj.actions[action](copy(state), actions, ...params);
if(result) {
state = copy(Object.assign(state, result));
if(state.render) {
obj.render(obj.views[state.view](state, actions));
}
}
}
actions[action] = actionWrapper;
});
obj.render(obj.views[state.view], {state, actions});
const actionFn = (action, ...params) => {
actions[action](...params);
return { emit: actionFn};
}
return { emit: actionFn}
}
import {app} from './app'
const HelloWorld = ({state, actions}) => (
<div>
<h1>Hello World {state.times}</h1>
<a href="javascript:void(0)" onClick={actions.update}>Update</a>
</div>
)
const actions = app({
state: {
view: 'HelloWorld',
times: 0
},
views: {
HelloWorld
},
actions: {
update: (state, actions) =>
({ times: state.times + 1 })
},
render: (Component, props) => {
const domContainerNode = document.getElementById('root');
let reactElement = React.createElement(Component, props);
ReactDOM.render(reactElement, domContainerNode);
ReactDOM.unmountComponentAtNode(domContainerNode)
}
});
actions.emit('update');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment