Skip to content

Instantly share code, notes, and snippets.

@leonardreidy
Created May 24, 2017 17:03
Show Gist options
  • Save leonardreidy/0b88d6cc0fcea27616845ec7cf395d5b to your computer and use it in GitHub Desktop.
Save leonardreidy/0b88d6cc0fcea27616845ec7cf395d5b to your computer and use it in GitHub Desktop.
Using React and Redux together - with annotations
// constants for serialisable actions
const INC = 'INCREMENT';
const DEC = 'DECREMENT';
// counter reducer
const counter = (state = 0, action) => {
switch(action.type){
case INC:
return state + 1;
case DEC:
return state - 1;
default:
return state;
}
}
// Dumb React counter component declared as simple
// function - no business logic
// Don't hardcode increment and decrement functions
// in component - add onIncrement and onDecrement
// props as callbacks and pass appropriate actions
// in the render method
const Counter = ({
value,
onIncrement,
onDecrement
}) => (
<div>
<h1>{value}</h1>
<button onClick={onIncrement}>+</button>
<button onClick={onDecrement}>-</button>
</div>
);
//
const { createStore } = Redux;
const store = createStore(counter);
// a function to render the current state of
// the store with React
// current state of the store is passed as a prop
// to the root component (Counter)
const render = () => {
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() =>
store.dispatch({
type: INC
})
}
onDecrement={() =>
store.dispatch({
type: DEC
})
}/>,
document.getElementById('root')
);
};
// render function is called any time the store
// state changes
store.subscribe(render);
// Call render to ensure that there is something
// in the body of the document at the outset
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment