Sometimes, we want to add nested routes with React Router v5.
In this article, we’ll look at how to add nested routes with React Router v5.
How to add nested routes with React Router v5?
To add nested routes with React Router v5, we can add Route
components in a Switch
component.
For instance, we write
const PrivateRoutes = () => {
return (
<>
<Header />
<Switch>
<Route path="/home" component={HomePage} />
<Route path="/dashboard" component={DashboardPage} />
<Route path="*" component={NotFoundPage} />
</Switch>
<Footer />
</>
);
};
const AuthRoutes = () => {
return (
<>
<Header />
<Switch>
<Route path="/login" component={LoginPage} />
<Route path="/sign-up" component={SignUpPage} />
<Route path="*" component={NotFoundPage} />
</Switch>
<Footer />
</>
);
};
const App = () => {
const history = createBrowserHistory();
return (
<div className="App">
<Router history={history}>
{isLoggedIn ? <PrivateRoutes /> : <AuthRoutes />}
</Router>
</div>
);
};
to add the PrivateRoutes
and AuthRoues
components.
They both have Switch
components wrapped around Route
components.
In App
, we render PrivateRoutes
or AuthRoutes
depending on the value of isLoggedIn
.
Conclusion
To add nested routes with React Router v5, we can add Route
components in a Switch
component.