Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle multiple routers in react

Tags:

reactjs

Let say we have a web application. It has usually many views, like index page, admin panel, help page, contact etc. I handle them using react-router-dom in the main index.js and it just works fine.

However now I faced problem with developing admin panel. It is one of the routes supported by the index.js router, but it contains its own menu with all actions available for admin.

How should I handle this, to only replace the content I need in the admin panel (admin actions menu stays), but not the whole content as I do from index.js router?

I tried to use the in the admin panel place for content replacement, but it either says too much recursion (If I duplicated the route for admin panel itself) or simply does not work saying nothing.

I'm react newbie and I don't even know how to call this problem.

Thanks for suggestions.

like image 203
Dreando Avatar asked Mar 25 '18 08:03

Dreando


1 Answers

If I understand your issue correctly, you can do that by nesting routes. Example assuming you use react-router 4.x.x: render Router or BrowserRouter etc. component (https://reacttraining.com/react-router/web/api/Router) once, at the top level, and then nest Route components. In your case you have main router in your index.js, so probably something like this:

<BrowserRouter>    <Route path="/" exact component={Main} />    <Route path="/some-page" component={SomePage} />    <Route path="/admin" component={Admin} /> </BrowserRouter> 

then, in your Admin component you don't create another Router, instead just render Routes again, so something like this:

<div className="admin-panel-container">   <AdminMenu />   <Route path="/admin/users" component={AdminUsers} />   <Route path="/admin/groups" component={AdminGroups} /> </div> 

so when URL matches /admin you'll see AdminMenu and component for a specific view in admin panel. You probably want to redirect from /admin to /admin/users or some dashboard, that depends on your specific application.

Now, if you have some layout elements surrounding your main router that you want to get rid of in admin routes, it's hard to say more without seeing some code example, but I guess you could create two components, for example, Layout and AdminLayout, each containing menus, header etc. and accepting children, and use them in every route depending on if it's admin or regular user route.

like image 75
simka Avatar answered Sep 23 '22 10:09

simka