Mark As Completed Discussion

Nested Routing

Nested routing is a powerful feature of React Router that allows you to create routes within routes, enabling you to render nested components based on the URL.

Imagine you have an application where you want to display a home page and a topics page that shows different topics to explore. Each topic can have its own sub-components and routes.

To create nested routes, you can define the parent route and its respective component, and then define child routes within the parent component. These child routes will be rendered in place of the parent component when the URL matches their path.

Here's an example of how to create a basic nested route using React Router:

JAVASCRIPT
1import { BrowserRouter as Router, Route } from 'react-router-dom';
2
3function App() {
4  return (
5    <Router>
6      <div>
7        <h1>Welcome to AlgoDaily!</h1>
8
9        <Route exact path="/" component={Home} />
10        <Route path="/topics" component={Topics} />
11      </div>
12    </Router>
13  );
14}
15
16function Home() {
17  return (
18    <div>
19      <h2>Home Page</h2>
20      <p>Welcome to the home page of AlgoDaily!</p>
21    </div>
22  );
23}
24
25function Topics() {
26  return (
27    <div>
28      <h2>Topics</h2>
29      <p>Choose a topic to explore:</p>
30      <ul>
31        <li><a href="/topics/algorithms">Algorithms</a></li>
32        <li><a href="/topics/data-structures">Data Structures</a></li>
33        <li><a href="/topics/interview-preparation">Interview Preparation</a></li>
34      </ul>
35
36      <Route path="/topics/algorithms" component={Algorithms} />
37      <Route path="/topics/data-structures" component={DataStructures} />
38      <Route path="/topics/interview-preparation" component={InterviewPreparation} />
39    </div>
40  );
41}

In this example, we have defined a Home component and a Topics component. The Topics component displays a list of topics and their corresponding links. When you click on a topic link, the respective component will be rendered within the Topics component.

This is just a basic example to demonstrate the concept of nested routing. In practice, you can have as many levels of nesting as you need, and each nested component can have its own set of child routes.

Nested routing in React Router allows you to create complex application structures with different components rendered based on the URL. It provides a flexible and scalable approach to handling multiple levels of routing within your React application.

Now, take a moment to run the provided code example in your own React project and observe the changes in the rendered components based on the URL. Try adding more nested routes and components to explore the full potential of nested routing.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment