Mark As Completed Discussion

Nested Routes with React Router

In complex web applications, you may need to render components within other components based on the current route. React Router provides support for creating nested routes, allowing you to build a nested component structure to handle different URL paths.

To create nested routes with React Router, you can configure Routes and nested Route components to match specific paths. Here's an example:

SNIPPET
1// replace with code relevant to content
2import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
3
4const App = () => {
5  return (
6    <Router>
7      <div>
8        <h1>My App</h1>
9        <Switch>
10          <Route exact path="/" component={Home} />
11          <Route path="/products" component={Products} />
12          <Route path="/products/:id" component={ProductDetails} />
13        </Switch>
14      </div>
15    </Router>
16  );
17};
18
19const Home = () => {
20  return <h2>Welcome to My App</h2>;
21};
22
23const Products = () => {
24  return (
25    <div>
26      <h2>Product List</h2>
27      <ul>
28        <li>Product 1</li>
29        <li>Product 2</li>
30        <li>Product 3</li>
31      </ul>
32    </div>
33  );
34};
35
36const ProductDetails = ({ match }) => {
37  const { id } = match.params;
38  return <h2>Details for Product #{id}</h2>;
39};

In this example, we define three routes - the root route, the '/products' route, and the '/products/:id' route. The Switch component ensures that only one matching route is rendered at a time. When the URL matches the path for a specific route, the corresponding component will be rendered.

By using nested Route components, you can create a nested component structure. For example, within the '/products' route, you can render a list of products, and within the '/products/:id' route, you can render the details of a specific product.

Nested routes provide a flexible way to manage the component hierarchy and handle different levels of nesting in your application. You can easily organize and navigate through different sections of your application by defining nested routes.

In a real-world scenario, this could be useful if you are building an e-commerce website. You can have a main route for '/products', which renders a list of products. When a user clicks on a specific product, the '/products/:id' route is matched, and the details of that product are displayed.

Overall, nested routes with React Router offer a powerful and intuitive way to handle complex routing scenarios in your React applications.

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