React Counter Example

In notebook:
Egghead Redux
Created at:
2016-07-09
Updated:
2016-07-09
Tags:
libraries React JavaScript pattern
Imports React to the app. Will use ​ReactDOM.render​ 
  const counter = (state = 0, action) => {
  switch (action.type) {
    ...
  }
}

const Counter = ({ value }) => (
  <h1>{value}</h1>
);

const { createStore } = Redux;
const store = createStore(counter);

const render = () => {
  reactDOM.render(
    <Counter value={store.getState()} />
    document.getelementById('root')
  )
}
Now implement the increment and decrement functionality
  const counter = (state = 0, action) => {
  switch (action.type) {
    ...
  }
}

const Counter = ({ 
  value ,
  // ++++
  onIncrement,
  onDecrement
  }) => (
  <h1>{value}</h1>
  <button onClick={onIncrement}>+</button>
  <button onClick={onDecrement}>+</button>
);

const { createStore } = Redux;
const store = createStore(counter);

const render = () => {
  reactDOM.render(
    <Counter value={store.getState()} 
    // ++++
    onIncrement = {() => 
      store.dispatch({
        type: 'INCREMENT'
      })
    }
    onDecrement = {() => 
      store.dispatch({
        type: 'DECREMENT'
      })
    }
    />,
    document.getelementById('root')
  )
}
Note, that the ​Counter​ is a “dumb” component, it does not contain any logic. Just transforms the application state into renderable output.