I have a parent component for all my website routes <App>
that wraps around all my routes such as /
, /about
, etc. It looks like:
<BrowserRouter>
<App>
<Route exact path="/" component={Index} />
<Route path="/post/:id" component={Post} />
</App>
</BrowserRouter>
I also have a backend management interface, used by an Admin, that I want to have a different parent component. In the end, it would look something like:
<BrowserRouter>
<Admin>
<Route exact path="/admin" component={AdminIndex} />
<Route path="/admin/posts" component={AdminPosts} />
</Admin>
</BrowserRouter>
But I cannot get this working. First of all, I tried having both router rules in the BrowserRouter
wrapped in a div
but that ended up rendering both the <App>
and <Admin>
component. How can I separate them so that when the router matches routes for <App>
, it renders that and when it matches routes for <Admin>
it only renders those components?
<BrowserRouter>
<Switch>
<Route path="/admin" component={Admin}/>
<Route path="/" component={App}/>
</Switch>
</BrowserRouter>
const App = (props) => (
<div>
<Route path="/post/:id" component={Post}/>
<Route exact path="/" component={AdminIndex}/>
</div>
);
const Admin = (props) => (
<div>
<Route path="/admin/posts" component={AdminPosts}/>
<Route exact path="/admin" component={AdminIndex}/>
</div>
);
If the '/admin' route is matched, the Admin
component will be rendered exclusively, which in turn renders whatever Route
is matched (same goes for the App
component). For more examples .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.