Bertuz
Bertuz

Reputation: 2576

how to define a react router's IndexRoute when using dynamic routing

What I have is a root route definition:

const rootRoute = {
    childRoutes: [{
        path: '/',
        component: require('./screens/Container'),
        appGlobalVars: appGlobalVars,
        childRoutes: [
            require('./routes/ListApps'),
            require('./routes/Settings'),
            require('./routes/Profile')
        ]
    }]
};


var runApp = (appGlobalVars) => {
    var routes = (
        <Provider store={store}>
            <Router history={ history } routes={rootRoute} />
        </Provider>
    );

    render(routes, document.getElementById('app'));
};

and some settings with nested dynamic routing:

./routes/Settings/index.js:

module.exports = {
    path: 'settings',
    getComponent(nextState, cb) {
        require.ensure([], (require) => {
            cb(null, require('../../screens/AppSettings'))
        })
    },
    getChildRoutes(partialNextState, cb) {
        require.ensure([], (require) => {
            cb(null, [
                require('./General'),
                require('./Users')
            ])
        })
    },
};

/settings is the parent component, which renders {this.props.children} react router passes. For example, if I navigate to /settings/general I'll have settings rendered, which in turn will render general as its child:

./routes/Settings/General.js

module.exports = {
    path: 'general',
    getComponent(nextState, cb) {
        require.ensure([], (require) => {
            cb(null, require('../../screens/AppSettings/General'))
        })
    }
};

This is OK, but what I would like to do is defining the default child component Settings should render if navigating to /settings.

In short: is there a way to define something like IndexRoute when using dynamic routing?

Upvotes: 0

Views: 1768

Answers (2)

nacho_dh
nacho_dh

Reputation: 1937

Since the method getIndexRoutes is deprecated, I noticed that indexRoute expects an object { component: SomeCompoent }, which is the schema of the object returned by getComponent, so I used getComponent to provide indexRoute as follows:

export default (store) => ({
  path : 'shops',
  childRoutes: [ 
    EditShopRoute(store),
  ],
  component: EntityLayout, // this renders always
  indexRoute: { // this renders only when route matches exactly /shops
    getComponent (nextState, cb) {
     require.ensure([], (require) => {
      const Shops = require('./containers/ShopsContainer').default
      const reducerShop = require('./modules/shops').default
      injectReducer(store, { key: 'shops', reducer: reducerShop })

      cb(null, Shops)

    /* Webpack named bundle   */
  }, 'shops')
  } }

})

Upvotes: 0

Related Questions