Redux – avoid to pass props down component tree manually – 4. Build container components more easily with connect()

With connect() you don’t have to manually write the container component as a Component class.

 
const CounterComponentContainer = connect(
		// store.state => props of child component. Normally it's extracted as a function called mapStateToProps()
		state => { 
			return {counter: state.counter} 
		}, 
		// store.dispatch => props of child component. Normally it's extracted as a function called mapStateToDispatch()
		dispatch => {
			return {onChange: (amount) => dispatch({type: 'counterChange', amount: amount})} 
		}
) (CounterComponent);    //connect() returns a function.  Here you invoke the returned function with the original component as the parameter.

//And the following is not needed any more. You can comment it out. 
// CounterComponentContainer.contextTypes = {
//		store: PropTypes.object
// };
 

And you can go even futher. You don’t have to give the conainer component a name.

CounterComponent = connect(
		
		state => { 
			return {counter: state.counter} 
		}, 
		
		dispatch => {
			return {onChange: (amount) => dispatch({type: 'counterChange', amount: amount})} 
		}
) (CounterComponent);  //CounterComponent will be changed from a reusable component to a container component


class AppComponent extends Component {
  render() {
    return (

      <div className="App">
        ...
        <CounterComponent/>   <!-- This is still a container component -->
        ...
      </div>

    );
  }
}

This is it! Nothing sucks any more!

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.