Connecting the AddTodo component

We are now going to start connecting our components to the Redux store. The presentational components can stay the same as before. We only create new components—container components—that wrap the presentational components, and pass certain props to them.

Let's connect the AddTodo component now:

  1. Create a new src/containers/ folder for all our container components.
  2. Create a new src/containers/ConnectedAddTodo.js file.
  3. In this file, we import the connect function from react-redux, and the bindActionCreators function from redux:
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
  1. Next, we import the addTodo action creator and the AddTodo component:
import { addTodo } from '../actions'
import AddTodo from '../components/AddTodo'
  1. Now, we are going to define the mapStateToProps function. Since this component does not deal with any state from Redux, we can simply return an empty object here:
function mapStateToProps (state) {
return {}
}
  1. Then, we define the mapDispatchToProps function. Here we use bindActionCreators to wrap the action creator with the dispatch function:
function mapDispatchToProps (dispatch) {
return bindActionCreators({ addTodo }, dispatch)
}

This code is essentially the same as manually wrapping the action creators, as follows:

function mapDispatchToProps (dispatch) {
return {
addTodo: (...args) => dispatch(addTodo(...args))
}
}
  1. Finally, we use the connect function to connect the AddTodo component to Redux:
export default connect(mapStateToProps, mapDispatchToProps)(AddTodo)

Now, our AddTodo component is successfully connected to the Redux store.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.162.247