If we use React to create our JavaScript app, we probably add a routing solution so that we can render different components if we go to different URLs.
React Router is a popular routing library to serve this purpose.
In this article, we’ll look at how to add nested routes with React Router version 5.
Add Nested Routes with React Router Version 5
We can nested routes with React Router version by nesting Route
components inside the function we pass into the render
prop.
To do this, we write:
import React from "react";
import { BrowserRouter, Route, Link } from "react-router-dom";
const FrontPage = () => <p>front page</p>;
const HomePage = () => <p>home page</p>;
const AboutPage = () => <p>about page</p>;
const Backend = () => <p>back end</p>;
const Dashboard = () => <p>dashboard</p>;
const UserPage = () => <p>user page</p>;
export default function App() {
return (
<div>
<BrowserRouter>
<Link to="/">front page</Link>
<Link to="/home">home page</Link>
<Link to="/about">about page</Link>
<Link to="/admin">back end</Link>
<Link to="/admin/home">dashboard</Link>
<Link to="/admin/users">user page</Link>
<Route path="/" component={FrontPage} exact />
<Route path="/home" component={HomePage} />
<Route path="/about" component={AboutPage} />
<Route
path="/admin"
render={({ match: { url } }) => (
<>
<Route path={`${url}/`} component={Backend} exact />
<Route path={`${url}/home`} component={Dashboard} />
<Route path={`${url}/users`} component={UserPage} />
</>
)}
/>
</BrowserRouter>
</div>
);
}
We have the FrontPage
, HomePage
, AboutPage
, Backend
, Dashboard
, and UserPage
route components.
We’ll use the when we define our routes.
Then in App
, we add the BrowserRouter
component so we can add the routes inside it.
We add the Link
component with the to
prop to add links that goes to the given route.
Then we add Route
components to map URL paths to components that are passed into the component
prop.
The path
prop lets us set the path of the route.
exact
lets us only load the component when the exact path is matched.
When we go to the URL path given, then the given component will load.
The last Route
component has the path
set to '/admin'
, which is the first part of the URL path.
The render
prop is set to a function that takes an object with the match.url
property.
We destructure that from the object, then pass them into the Route
components we return in the function.
This lets us map route with the path starting with /admin
to the given components.
So when we go to /admin
, we see the Backend
component displayed.
If we go to /admin/home
, we see the Dashboard
component rendered.
And if we go to /admin/users
, we see the UserPage
component rendered.
Therefore, when we click on the links, we see the content of each component displayed.
Conclusion
We can add nested routes with React Router 5 easily by nested Route
components.