Redux – avoid to pass props down component tree manually – 3. Use an extra container component to keep the original one reusable

So a "container" component will be introduced to wrap the original one. The container component will adapt the store structure to "input parameters" the original one needs. Therefore, the original one doesn’t need to access store directly and will be reusable again.

//The reusable component, which doesn't access store any more 
class CounterComponent extends Component {
    constructor(props){
        super(props);
    }

    render(){
        return (

            <div>
                <h2>Counter</h2>
                <h3>{this.props.counter.value}</h3>    
                <div>
                    <button onClick={ e => this.props.onChange(1)}>+</button>   
                    <button onClick={ e => this.props.onChange(-1)}>-</button>    
                </div>
            </div>
        );
    }

}

// the container component, which gets data from the store and passes them as props to the reusable one 
class CounterComponentContainer extends Component {

    render(){
    	 return (        		
    			 <CounterComponent 
    			 	counter={this.context.store.getState().counter}
    			 	onChange={(amount) => this.context.store.dispatch({type: 'counterChange', amount: amount})}
    			 />	
    	        );
    }
}

CounterComponentContainer.contextTypes = {
		store: PropTypes.object
};




class AppComponent extends Component {
  render() {
    return (

      <div className="App">
        ...
        <CounterComponentContainer/>   <!-- Now it uses the container component -->
        ...
      </div>

    );
  }
}

Leave a Comment

Your email address will not be published.

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