Skip to main content

Nested Routes in React Routing

Nested routes in React Router enable you to create hierarchical routing structures within your application. This powerful feature allows you to manage the rendering of child components based on the current URL. In this tutorial, we'll explore nested routes in React Router with sample code and simple explanations.

Creating Nested Routes

To create nested routes, you'll need to add the Route component as a child of the parent component that you want to display the child route within. Here's an example:

App.js
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import User from './User';

function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/user" component={User} />
</Switch>
</BrowserRouter>
);
}

export default App;
User.js
import React from 'react';
import { Route, Link, Switch, useRouteMatch } from 'react-router-dom';
import UserProfile from './UserProfile';
import UserSettings from './UserSettings';

function User() {
const { path, url } = useRouteMatch();

return (
<div>
<h1>User</h1>
<ul>
<li>
<Link to={`${url}/profile`}>Profile</Link>
</li>
<li>
<Link to={`${url}/settings`}>Settings</Link>
</li>
</ul>

<Switch>
<Route path={`${path}/profile`} component={UserProfile} />
<Route path={`${path}/settings`} component={UserSettings} />
</Switch>
</div>
);
}

export default User;

In this example, we've created a parent route ("/user") that renders the User component. Inside the User component, we've defined two child routes ("/user/profile" and "/user/settings") that render the UserProfile and UserSettings components, respectively.

Using useRouteMatch

The useRouteMatch hook from the react-router-dom package can be used to extract the current URL path and construct nested route paths. In the example above, we've used useRouteMatch to obtain the path and url values, which are then used to create the nested routes and their corresponding Link components.

Conclusion

In this tutorial, we've learned how to create nested routes in React Router using the Route component and the useRouteMatch hook. Nested routes allow you to build hierarchical routing structures and manage the rendering of child components based on the current URL.

Practice creating nested routes in your applications to gain a better understanding of their capabilities. As you gain experience, you'll be able to build more complex and interactive routing structures for your React applications.