Skip to content

Instantly share code, notes, and snippets.

@joshwcomeau
Created December 11, 2015 12:29
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 joshwcomeau/2938fed6cc2bf3126f65 to your computer and use it in GitHub Desktop.
Save joshwcomeau/2938fed6cc2bf3126f65 to your computer and use it in GitHub Desktop.
Really basic Redux + React example
"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