Reputation: 1779
I have a parent component which loads some data from the backend in the componentWillMount
method. This comes from a single config endpoint which should only be called once. What I'd like to do load the data into his parent component and then wrap a number of child components with this state. To contextualize this the parent component is a navbar and a footer for a dashboard, the children would be views within this dashboard, i.e. the dashboard page content. React-Router's documentation explains that {this.props.children}
is the preferred method for handling this but doesn't seem to explain how to pass state down to the children. How do I go about doing this?
Also it might be worth illustrating my routes:
<Router history={browserHistory}>
<Route path='/' onEnter={redirectWww} />
<Route
path='/dashboard'
component={DashboardContainerWrapper}
onEnter={requireAuth}>
<Route path='/dashboard/' component={DashboardIndex}/>
<Route path='/dashboard/some/view' component={DashboardSomeView}/>
</Route>
</Router>
Upvotes: 0
Views: 683
Reputation: 91
I can pass state and function from parent to children just like:
<Router history={browserHistory}>
<Route path='/' onEnter={redirectWww} />
<Route
path='/dashboard'
component={() => (
<DashboardContainerWrapper browserHistory={browserHistory} /> )}
onEnter={requireAuth} />
<Route path='/dashboard/' component={DashboardIndex}/>
<Route path='/dashboard/some/view' component={DashboardSomeView}/>
</Route>
</Router>
Upvotes: 0
Reputation: 1074
Actually just had to do something similar today. What I did was I used React.cloneElement to inject the parent components state into the child components. In your render method
{React.Children.map(this.props.children, (child) =>
React.cloneElement(child, {...this.state})
)}
Upvotes: 2