Reputation: 11
I have my app and I want to add an admin routes. The problem is my header and footer are rendered on every route so when I'm trying to access admin panel they are rendered too. How can I separate 2 different routes for 2 different apps (not exactly but I hope u'll understand).
This is how my router looks like:
<Router>
<Container>
<Header/> // it is intended
<Switch>
<Route exact path='/' component={ Home } />
<Route path='/news/:category/:id/:title' component={ SingleArticle } />
<Route path='/news' component={ Home } />
<Route path='/live' component={ Live } />
<Route path='/admin' component={ AdminPanel } /> //here I want all my admin routes which generates its own header and footer
<Route path='*' component={ NotFound } />
</Switch>
<Footer /> // it is intended
</Container>
</Router>
Upvotes: 1
Views: 917
Reputation: 41
You can use useLocation()
Hook to find paths and separate routes.
eg:
import { useLocation } from 'react-router-dom'
if (useLocation().pathname.includes("/admin")) {
return (
<Switch>
<Route exact path="/admin" component={Admin} />
</Switch>
);
} else {
return (
<div className="App">
<Navbar />
<Switch>
// Routes goes
</Switch>
</div>
);
Upvotes: 0
Reputation: 742
You can make use of a layout type component that takes a component as a prop, adds the necessary components to it and returns an new component like so:
const Layout = ({ children }) => {
return (
<section>
<Header/>
{children}
<Footer/>
</section>
)
}
Then any component you want to render with the header and footer you can declare as a child of the layout component:
<Router>
<Container>
<Switch>
<Route path='/admin' component={ AdminPanel } /> //here I want all my admin routes which generates its own header and footer
<Layout>
<Route exact path='/' component={ Home } />
<Route path='/news/:category/:id/:title' component={ SingleArticle } />
<Route path='/news' component={ Home } />
<Route path='/live' component={ Live } />
<Route path='*' component={ NotFound } />
</Layout>
</Switch>
</Container>
</Router>
Upvotes: 0
Reputation: 1833
You can have different routes for admin and non-admin. You can do following:
if(admin) {
return (
<Router>
<Header>
// ... routes here
</Header>
</Router>
)
} else {
return (
<Router>
<AdminHeader />
// ... routes
</Router>
)
}
Upvotes: 3