⊗jsrtPmRtNR 27 of 47 menu

Nested Routes in React Router

In this lesson we will get acquainted with nested routes. Run the application we made in the previous lesson. Clicking on the links takes us to a separate page with the product. Let's say it's inconvenient for us to have it this way, and we'd like the list of products and the product page to be displayed side by side, on the same screen, for greater clarity. Let's do it this way.

To do this, let's open the main.jsx file and simply make our product page route a child route of the root route, or in other words, "nest" it into the root route. To do this, we'll use another property of the children route object:

const router = createBrowserRouter([ { path: '/', element: <Root />, errorElement: <ErrorPage404 />, children: [ { path: 'products/:productId', element: <Product />, }, ], }, ]);

We click on the links again, but we don't see anything to the right of the product list. This is because we haven't told the root route where we want to display its child routes.

The Outlet component will help us render child route elements in the parent route. Let's import it from the library into the root route file:

import { Outlet } from 'react-router-dom';

Then we'll wrap it in a div #product and add it to the layout for the root route at the end of the markup after the closing tag nav, and wrap the whole structure in another div #main:

return ( <div id="main"> <nav> <a href={`/products/1`}>Product1</a> <a href={`/products/2`}>Product2</a> </nav> <div id="product"> <Outlet /> </div> </div> );

By clicking on the links, we now see both the product list and the product page.

Let's add some styles to our index.css:

h1, h2 { margin: 0; } div#main { display: flex; margin: 20px; } div#product { margin-left: 40px; }

Take the application you created in the assignment for the previous lesson. Using the lesson materials, make the route for the student page nested in the root.

Now make it so that when you click on the links, both the list of students and the student page are displayed on the screen.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline