Skip to content

Instantly share code, notes, and snippets.

@pdewouters
Last active March 27, 2016 11:16
Show Gist options
  • Save pdewouters/2a6de8c3914e1db62da1 to your computer and use it in GitHub Desktop.
Save pdewouters/2a6de8c3914e1db62da1 to your computer and use it in GitHub Desktop.
Redux Container
// containers/Container.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import actionCreator from './actions/index'
import { bindActionCreators } from 'redux'
class Container extends React.Component {
render(){
return (
<div>Hello World</div>
)
}
}
// passes state as props to component
function mapStateToProps(state){
return {
something //something: state.something
}
}
// dispatch notifies reducers when action happens
function mapDispatchToProps(dispatch){
// you can now call this.props.actionCreator() to dispatch an action
// reducers will receive this action
return bindActionCreators({ actionCreator: actionCreator }, dispatch)
}
// connect() connects the react component with the redux store
export default connect(mapStateToProps, mapDispatchToProps)(Container)
// actions/index.js
const MY_ACTION = 'MY_ACTION'
export function actionCreator(item){
return {
type: MY_ACTION,
payload: item
}
}
// reducers/index.js
import { combineReducers } from 'redux'
import MyReducer from './reducers/my_reducer'
const rootReducer = combineReducers({
key: MyReducer
})
export default rootReducer
// reducers/my_reducer.js
// state argument is not app state, just this reducers state
export default function(state = null,action){
switch ( action.type ) {
case 'MY_ACTION':
return action.payload
break
default:
return state
break
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment