Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modularize routes in react-router

Is there a way with react-router to modularise your routes, then just import them and assemble them?

So instead of this:

  <Router>
    <Route path="/" component={App}>
      <Route path="inbox" component={Inbox}>
        <Route path="messages/" component={AllMessages} />
        <Route path="messages/:id" component={Message} />
      </Route>
      <Route path="calendar" component={Calendar}>
        <Route path="year" component={Year}>
          <Route path="month" component={Month}>
            <Route path="week" component={Week}/>
          </Route>
        </Route>
      </Route>
    </Route>
  </Router>

You could do something like that:

let InboxRoutes = React.createClass({
  render: function(){
    return (
      <Route path="inbox" component={Inbox}>
        <Route path="messages/" component={AllMessages} />
        <Route path="messages/:id" component={Message} />
      </Route>
    );
  }
});

<Router>
    <Route path="/" component={App}>
      <InboxRoutes/>
      <CalendarRoutes/>
    </Route>
  </Router>

I get: Warning: Location did not match any routes

like image 434
MoeSattler Avatar asked Dec 23 '15 11:12

MoeSattler


1 Answers

One solution is to wrap them in variables:

let InboxRoutes = (
    <Route path="inbox" component={Inbox}>
        <Route path="messages/" component={AllMessages} />
        <Route path="messages/:id" component={Message} />
    </Route>
)

let CalendarRoutes = (/* define routes like above */)

let routes = (
    <Router>
        <Route path="/" component={App}>
            {InboxRoutes}
            {CalendarRoutes}
        </Route>
    </Router>
)

render(routes, document.getElementById("app"))

Note: You should remember to put in the render method of parent routes {this.props.children}

like image 105
ali404 Avatar answered Nov 14 '22 04:11

ali404