reactjsreact-routerreact-router-componentreact-routing

React Nested routing issue


my router looks like the following,

[
  { 
    path: '/',
    component: App,
    childRoutes: [
      { 
        path: 'dashboard', 
        getComponent: function(location, cb) {
            require.ensure([], function(require) {
              cb(null, require('../plugins/dashboard/index'))
            })
        },
        childRoutes: [
            {
                path: '/:id', 
                getComponent: function(location, cb) {
                    require.ensure([], function(require) {
                      cb(null, require('../plugins/dashboard/saved_dashboard'))
                    })
                }
            }
        ]
      },
      { 
        path: 'profile',
        getComponent: function(location, cb) {
            require.ensure([], function(require) {
              cb(null, require('../plugins/profile/index'))
            })
          }
      }
    ]
  }
];

And my menu component sample code looks like

<ul id='menu'>
  <li>
    <Link to='dashboard'>dashboard</Link>
  </li>

  <li>
    <Link to='dashboard/mydashboard'>my dashboard</Link>
  </li>

  <li>
    <Link to='profile'>profile</Link>
  </li>
</ul>

the problem is when I click 'my dashboard' then it routes to

localhost/dashboard/mydashboard

from here if I click 'my dashboard' again it will routing to

localhost/dashboard/mydashboard/dashboard/mydashboard

and keep on going.

How to fix this issue? where I did the mistake? or I have to do anything more in the configuration?


Solution

  • The reason for that is that to parameter of Link takes the absolute path and your paths are relative...

    So to fix it, it should look like:

    <ul id='menu'>
      <li>
        <Link to='/dashboard'>dashboard</Link>
      </li>
    
      <li>
        <Link to='/dashboard/mydashboard'>my dashboard</Link>
      </li>
    
      <li>
        <Link to='/profile'>profile</Link>
      </li>
    </ul>