Skip to content

Instantly share code, notes, and snippets.

@rrdelaney
Created July 3, 2017 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rrdelaney/3d30640d91d0ca81b58e9fc0a80daad6 to your computer and use it in GitHub Desktop.
Save rrdelaney/3d30640d91d0ca81b58e9fc0a80daad6 to your computer and use it in GitHub Desktop.
Mini React/Redux
<div id="root" />
const React = {
_createStringElement(tag, props, children) {
const el = document.createElement(tag)
if (props) {
Object.entries(props).forEach(([key, value]) => {
el.setAttribute(key, value)
})
}
if (children.length) {
children.forEach(child => {
if (child === null || child === undefined) return
const isTextNode = typeof child === 'string' ||
typeof child === 'number'
const nextNode = isTextNode
? document.createTextNode(child)
: child
el.appendChild(nextNode)
})
}
return el
},
createElement(element, props, ...children) {
if (typeof element === 'string') {
return React._createStringElement(element, props, children)
} else if (typeof element === 'function') {
return element({ ...props, children })
} else {
return null
}
},
render(component, node) {
if (node.firstChild) {
node.replaceChild(component, node.firstChild)
} else {
node.appendChild(component)
}
}
}
const Redux = {
createStore: reducer => ({
_watchers: [],
_state: reducer(undefined, { type: '@@INIT'}),
dispatch(action) {
this._state = reducer(this._state, action)
this._watchers.forEach(w => {
w(this._state)
})
},
subscribe(watcher) {
this._watchers.push(watcher)
},
getState() {
return this._state
}
})
}
const initialState = 1
const reducer = (state = initialState, action) => {
switch(action.type) {
case 'INCREMENT': return state + 1
case 'DECREMENT': return state - 1
default: return state
}
}
const store = Redux.createStore(reducer)
const App = ({ state }) => <p>Counter: {state}</p>
const root = document.getElementById('root')
React.render(<App state={store.getState()} />, root)
store.subscribe(state => {
React.render(<App state={state} />, root)
})
setInterval(() => {
store.dispatch({ type: 'INCREMENT' })
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment