Skip to content

Instantly share code, notes, and snippets.

@sivadass
Created July 3, 2017 17:46
Show Gist options
  • Select an option

  • Save sivadass/8605b83dbba73cf80ae27e7e9f156ac0 to your computer and use it in GitHub Desktop.

Select an option

Save sivadass/8605b83dbba73cf80ae27e7e9f156ac0 to your computer and use it in GitHub Desktop.
Minimal React Redux Setup
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'
// React component
class Counter extends Component {
render() {
return (
<div>
<button onClick={this.props.onIncreaseClick}>+</button>
<span>{this.props.value}</span>
<button onClick={this.props.onDecreaseClick}>-</button>
<input type="text" onChange={this.props.onFetch}/>
</div>
)
}
}
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncreaseClick: PropTypes.func.isRequired,
onDecreaseClick: PropTypes.func.isRequired,
onFetch: PropTypes.func.isRequired
}
// Actions
const increaseAction = { type: 'increase' }
const decreaseAction = { type: 'decrease' }
const fetchAction = { type: 'fetching' }
// Reducer
function counter(state = { count: 0 }, action) {
const count = state.count
switch (action.type) {
case 'increase':
return { count: count + 1 }
case 'decrease':
return {count: count - 1}
case 'fetching':
return {count: count + 100}
default:
return state
}
}
// Store
const store = createStore(counter)
// Map Redux state to component props
function mapStateToProps(state) {
return {
value: state.count
}
}
// Map Redux actions to component props
function mapDispatchToProps(dispatch) {
return {
onIncreaseClick: () => dispatch(increaseAction),
onDecreaseClick: () => dispatch(decreaseAction),
onFetch: () => dispatch(fetchAction)
}
}
// Connected Component
const App = connect(
mapStateToProps,
mapDispatchToProps
)(Counter)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment