Let’s React-Redux !! -part 2

Sahil Sharma
2 min readMay 13, 2016

--

Now lets move to writing the BookList container. What CONTAINER ? We were talking about components till now.

A container is nothing but a smart component. What is meant be a smart component. And if I make a smart component , why the hell would I make a dumb component ? All these questions are valid and natural to come to mind . Please see this blogpost to know the difference between smart components and dumb components.

Carrying on with the BookList container.Check out the following code:

import React, { Component } from ‘react’;
import {connect} from ‘react-redux’;
import {selectBook} from ‘../actions/index’;
import { bindActionCreators } from ‘redux’;
class BookList extends Component {
renderList() {
return this.props.books.map( (book) => {
return (
<li
key={book.title}
onClick={() => this.props.selectBook(book)}
className=”list-group-item”>
{book.title}
</li>
)
})
}
render() {
return (
<ul className=”list-group col-sm-4">
{this.renderList()}
</ul>
);
}
}
function mapStateToProps(state) {
return {
books: state.books
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ selectBook: selectBook }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(BookList);

This piece of code is very important in terms of React-Redux concepts.

As I explained in my earlier blogposts, react is just for UI, Redux is just for state. To make both of these pieces to work together smoothly, we use a library called ‘react-redux’ (see line #2). Now take a look at the function mapStateToProps ,it takes the state as a parameter and returns an object. Simple enough , not really , that is when the last line comes into picture. Similarly mapDispatchToProps is the method which acts as a glue between react component and action creator(action creator will be explained in future posts, for now you can just think of it as a simple method which has a type denoting the type of action, and a payload). Following is a very simple example of the action creator used in the component.

export function selectBook(book) {
return {
type: ‘BOOK_SELECTED’,
payload: book
}
}

What the last line of the code does is make sure that redux state is wired to the react component BookList. It is due to this line , that the newly updated redux state is available in the component as props.

NEXT PART

--

--