maxcountryman
maxcountryman

Reputation: 1779

How do I pass state from a parent (wrapper component) to its children with react-router?

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

Answers (2)

bbaoooo
bbaoooo

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

Tyler Iguchi
Tyler Iguchi

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

Related Questions