Last active
July 20, 2017 23:04
-
-
Save honewatson/355da710216afa90c2daed6e44403325 to your computer and use it in GitHub Desktop.
Basic Hyperapp Style application for React
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
| 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} | |
| } |
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 {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