Redux with React, Redux Series II

Redux Logo

Background

First we must separate our react component into two different types, and they are container and components. Containers are components that interacts with redux. They handle the data and state management. Sometimes they are refer to as “smart component”. Components are sometimes refer to as “dumb components”. They only deal with markup and styles. They receive props from containers and display the data.

Setup

I’m going to show you the following steps with my recipe app. You can view demo here or view source code here.Recipebox Github

  1. First we must install redux-react
1
npm install redux react
  1. Next we connect our redux with react in our index.js (where we do all the exporting)
1
2
3
4
5
6
7
8
9
10
11
12
13
//index.js
import { createStore } from 'redux';
import reducer from './reducers';
import { Provider } from 'react-redux';
...
const store = createStore(reducer);
...
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
  1. Now we go to our container which is App.js and import the following modules and we connect mapStateToProps and mapDispatchToProps to our App.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// App.js
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as RecipeActions from '../actions/index';
...
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(RecipeActions, dispatch)
})

const mapStateToProps = (state) => {
return {
recipes: state.recipes
}
};
...
connect connect(mapStateToProps, mapDispatchToProps)(App);
  1. If you do the above step correctly, now we get actions and state as our props. We can test by using console.log.
1
2
3
// App.js
// console.log(this.props)
const {actions, recipes} = this.props;
  1. Now I can pass the state and actions as props to my components (aka. dumb components). In my example I passed it to the Recipelist component and AddForm component. Then I can use the actions and states in my components.
1
2
3
4
5
6
7
8
9
10
11
12
//App.js
<Grid>
<Header />
<Recipelist
recipes={recipes}
deleterecipe={actions.deleteRecipe}
editrecipe={actions.editRecipe}
/>
<AddForm
addrecipe={actions.addRecipe}
/>
</Grid>

Conclusion

We successfully move our state to redux. As our app gets bigger having a central store management is imperative. This is not it. With redux install we can track our actions and state via Redux Dev tool. In the next blog post, I’ll share how to use the debugging tool and some extra tips.