Moezalez Moezalez - 2 months ago 26
React JSX Question

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

Answer

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}