Redux Counter Example

In this example below you will see how to do a Redux Counter Example with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by intrepion, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright intrepion ©
  • HTML
  • CSS
  • JavaScript
    <div id="root"></div>


/*Downloaded from https://www.codeseek.co/intrepion/redux-counter-example-obaYXq */
    


/*Downloaded from https://www.codeseek.co/intrepion/redux-counter-example-obaYXq */
    /*
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'
*/

const { PropTypes } = React;
const { createStore } = Redux;
const { Provider, connect } = ReactRedux;

// React component
class Counter extends React.Component {
  render () {
    const { value, auto, onIncreaseClick } = this.props
    return (
      <div>
        <span>{value}</span>
        <button onClick={onIncreaseClick}>Increase</button>
        <input type='checkbox' checked={auto} />
      </div>
    )
  }
}

Counter.propTypes = {
  value: PropTypes.number.isRequired,
  onIncreaseClick: PropTypes.func.isRequired,
  auto: PropTypes.bool.isRequired,
}

// Action
const increaseAction = {type: 'increase'}
const autoAction = {type: 'auto'}

// Reducer
function counter (state = {count: 0, auto: false}, action) {
  let count = state.count
  switch (action.type) {
    case 'increase':
      return {
        ...state,
        count: count + 1,
      }
    case 'auto':
      console.log(state.auto)
      return {
        ...state,
        auto: !state.auto
      }
    default:
      return state
  }
}

// Store
let store = createStore(counter)

// Map Redux state to component props
function mapStateToProps (state) {
  return {
    value: state.count,
    auto: state.auto,
  }
}

// Map Redux actions to component props
function mapDispatchToProps (dispatch) {
  return {
    onIncreaseClick: () => dispatch(increaseAction),
    onAutoChange: () => dispatch(autoAction),
  }
}

// Connected Component
let App = connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter)

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

Comments