Mike Chaliy
Mike Chaliy

Reputation: 26658

How to define child routes as react components in react-router?

I have main.js:

import { render } from 'react-dom';
import { browserHistory, Router, Route, IndexRoute } from 'react-router';

import Home from './containers/Home';
import ApplicationsRoutes from './applications/routes';

render((
  <Router history={browserHistory}>
    <Route path="/" component="div">
      <IndexRoute component={Home} />      
      <ApplicationsRoutes />
    </Route>
  </Router>
), document.getElementById('app'));

And /application/routes.js :

import { browserHistory, Router, Route, IndexRoute } from 'react-router'

import ApplicationsHome from './containers/ApplicationsHome';

export default () => (
  <Route path="applications" component={ApplicationsHome} />
);

I was expecting that route from /application/routes.js will be added to the main router and so ApplicationsHome will be rendered for path /applications

Unfortunately, this is not a case. I am getting error:

Location "/applications" did not match any routes

For me it looks like such a way to compose Router does not work, but I cannot understand what is right way to do this.

Upvotes: 1

Views: 2514

Answers (2)

nanobar
nanobar

Reputation: 66355

For singular routes you can export your route as a JSX element:

export default <Route path="applications" component={ApplicationsHome} />;

And include it like this:

{SomeRoute}

For multiple routes you can't export them as you have in a function, you'll get a JSX error saying you can't have adjacent components without a wrapping element. In that case you would have to do:

export default (
  <Route>
    <Route path="/about" component={About} />
    <Route path="/services" component={Services} />
  </Route>
);

And use it:

{ApplicationsRoutes}

Upvotes: 2

taion
taion

Reputation: 2837

In general, when you do this, you should consider using the PlainRoute syntax instead of the JSX syntax, then use getChildRoutes on the parent routes to resolve the child routes, per the huge-apps example: https://github.com/rackt/react-router/tree/master/examples/huge-apps

This will then let you easily configure code-splitting and dynamic routes down the road.

Upvotes: 3

Related Questions