nicholas
nicholas

Reputation: 100

Connect state with children components

I'm trying to bind store with children components. I have AppContainer.js:

// here I'm binding store value to props
function mapStateToProps(store, props){
    return {
        user: store.userInfo.loaded ? store.userInfo.userData : '%noname%'
    }
}

componentDidMount(){
    store.dispatch(fetchUser()).then(() =>
        console.log(store.getState())
    )
}

render(){
    return <Application routes={this.props.routes} user={this.props.user}/>
}

export default connect(mapStateToProps)(ApplicationContainer);

In Application.js I'm passing params to direct child and children:

render(){

    return  <div className="component">
                <Header title="Home" user={this.props.user} routes={this.props.routes}/>
                {this.props.children} // Here is Home Component
            </div>;
}

And want to get state value in Home.js (one of the children):

render() {
        return <h5>Welcome back, {this.props.user.name}</h5>
    }

So, the question is: What is the proper way to push store values to child components?

Upvotes: 0

Views: 227

Answers (1)

Mayday
Mayday

Reputation: 5136

You could use React.children and cloneElement in order to achieve that:

return (
  <div className="component">
    <Header title="Home" user={this.props.user} routes={this.props.routes}/>
    {React.Children.map(this.props.children, child =>
      React.cloneElement(child, {
        ...this.props
      })
    )}
  </div>;
);

Upvotes: 1

Related Questions