Search code examples
reactjsreact-routerreact-router-redux

React routes move sub-routes to separate module?


Is it possible todo the following with React Route?

Main

  <Routes handler={App}>
    <Profile path="profile" />
    <Explore path="explore" />
  </Routes>

Profile

    <Route>
      <Route name="dashboard" handler={ProfileDashboard} />
      <Route name="repos" handler={ProfileRepos} />
    </Route>

Explore

    <Route>
      <Route name="home" handler={ExploreHome} />
      <Route name="showcase" handler={ExploreShowcase} />
    </Route>

Solution

  • You can achieve that with React Router! :)

    But I would suggest you to check it out the "plain routes" way to configure your routes:

    https://github.com/ReactTraining/react-router/blob/v2.8.1/docs/guides/RouteConfiguration.md#configuration-with-plain-routes

    Using this, you will start working with a routes object, and you can just require another routes and create your route based on those combinations. Something like that:

    const routes = {
        path: '/',
        component: App,
        childRoutes: [
            require('./profile'),
            require('./explore')
        ]
    }
    

    Then in your profile.js (you can do the same to explore.js) file, you will have something like that:

    /* Import the ProfileDashboard and ProfileRepos here */
    
    const profileRoutes = {
        path: 'profile',
        childRoutes: [{
            path: 'dashboard',
            component: ProfileDashboard
        }, {
            path: 'repos',
            component: ProfileRepos
        }]
    };
    

    And this way you can achieve what you want.

    If you really can't use plain routes, you may do something like that:

    <Route path="/" component={App}>
        { require('./profile') }
        { require('./explore') }
    </Route>
    

    And your profile.js, for example:

    module.exports = (
        <Route path="profile">
            <Route path="dashboard" component={ProfileDashboard} />
            <Route path="dashboard" component={ProfileRepos} />
        </Route>
    );
    

    I don't know what React Router version you are using, but you can achieve that in any version, but, as a suggestion, try using the latest one. Since it handle lots of cool stuff.

    Hope it helps!