Zigrivers
Zigrivers

Reputation: 409

How to properly handle child routes in react-router (routing works, but URL grows with each click)

I am in the process of learning how to use react-router. My routing is working correctly, meaning that I get the views I need as I click the appropriate links. I have a view that has nested/child routes. Clicking on these child links does take me to the appropriate view, but it doesn't update the browser's URL as I would like.

I start with the the IndexRoute for the view. The browser's URL starts looking like this, which is what I want:

http://localhost:3000/administration

As I click the different child routes, it keeps appending the child route's path onto the URL, so that after a couple of clicks the browser's URL ends up looking soemthing like this:

http://localhost:3000/administration/administration/administration/administration/administration/administration/administration/administration/company-goals

When what I want is the browser's URL to be this:

http://localhost:3000/administration/company-goals

I have a route structure set up like the following:

<Route path="/" component={HomePage}> <IndexRoute component={HomeView} /> <Route path="budgets" component={BudgetView} /> <Route path="administration" component={adminViews.Administration}> <IndexRoute component={adminViews.Home} /> <Route path="department-budgets" component={adminViews.DepartmentBudgets} /> <Route path="price-list" component={adminViews.PriceList} /> <Route path="company-goals" component={adminViews.CompanyGoals} /> </Route> </Route>

The Administration view has a tabbed navigation, with a tab for each of the Administration's view's child routes.

I am changing the route when the user clicks on a tab with a function like the following:

selectedTab( tab ) { const menu = menuItems.find((item) => { return item.payload === tab.value; }); history.pushState(null, menu.uriPath); }

And the uriPath for each of the routes is defined as follows:

menuItems = [ { payload : '1', text : 'Home', uriPath : 'administration' }, { payload : '2', text : 'Department Budgets', uriPath : 'administration/department-budgets' }, { payload : '3', text : 'Price List', uriPath : 'administration/price-list' }, { payload : '4', text : 'Company Goals', uriPath : 'administration/company-goals' } ];

Any help would be greatly appreciated. I feel like I'm missing something very basic, but I haven't been able to identify what I'm doing wrong.

Thank you!

Upvotes: 4

Views: 760

Answers (1)

Jim Bolla
Jim Bolla

Reputation: 8295

Put a / at the beginning of your uriPaths.

Upvotes: 5

Related Questions