Created
December 11, 2015 12:29
-
-
Save joshwcomeau/2938fed6cc2bf3126f65 to your computer and use it in GitHub Desktop.
Really basic Redux + React example
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
"use strict"; | |
const connect = ReactRedux.connect; | |
const Provider = ReactRedux.Provider; | |
// REDUCER | |
const defaultState = { count: 0 }; | |
const appReducer = (state = defaultState, action) => { | |
switch ( action.type ) { | |
case 'increment': | |
return _.extend({}, state, { count: state.count+1 }); | |
case 'decrement': | |
return _.extend({}, state, { count: state.count-1 }); | |
default: | |
return state; | |
} | |
}; | |
// STORE | |
store = Redux.createStore(appReducer) | |
store.dispatch({ | |
type: 'increment' | |
}); | |
// ACTION CREATORS | |
const increment = () => { | |
return { type: 'increment' } | |
}; | |
const decrement = () => { | |
return { type: 'decrement' } | |
}; | |
// PRESENTATION COMPONENT | |
const Counter = ({ count, onIncrement, onDecrement}) => { | |
return ( | |
<div className='counter'> | |
<h1 className='count'>{count}</h1> | |
<button onClick={onIncrement}>+</button> | |
<button onClick={onDecrement}>-</button> | |
</div> | |
); | |
}; | |
// CONTAINER WRAP | |
function stateSelect(state) { | |
return { | |
count: state.count | |
} | |
} | |
function dispatchSelect(dispatch) { | |
return { | |
onIncrement: () => dispatch(increment()), | |
onDecrement: () => dispatch(decrement()) | |
}; | |
} | |
const CounterContainer = connect(stateSelect, dispatchSelect)(Counter) | |
// RENDER | |
const render = () => { | |
ReactDOM.render( | |
<Provider store={store}> | |
<CounterContainer /> | |
</Provider>, | |
document.getElementById('app') | |
); | |
}; | |
render(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment