,

My React Router Notes – Nested Pages

Posted by

Before diving into nested pages with react router, I recommend reviewing my intro to react router blog posted here:

My React Router Notes – Intro – Russ Maxwell’s Blog

With react router, you also have the ability to setup a nested page structure for a react application.  The question is why do you need one if I can just implement all of my routes as individual parent routes within createBrowserRouter() below:

You’ll likely will have some components that will apply to all pages.  For Example, a Navigation Bar and Footer is usually on every single page in your site.   To persists those components across pages, the easiest approach is to adopt the nested page structure.   The parent page is going to contain your components that you want to make visible across all of the child pages.  I call it my layout page.   Setting this up, I’ll create a layout.jsx page within the pages directory.

Also, I created a navbar component within my components directory and added some styling to it.  It looks like:

Now that I have my navbar component, I’ll need to add it to my new Layout.jsx page.  It looks like:

The nested page structure is also setup in your App.jsx.  Within App.jsx, set the layout page as the parent and group the remaining pages within the children element as an array of objects.   It looks like the following:

Wait, what will happen to the landing page now that it’s a child?   Well, this is why you add and set the index property to true for the landing page.  This instructs react router to render this page when hitting the path defined in the parent.  Okay loading up the page within VS Code by running npm run dev in the terminal and I see the following:

Wait, I don’t see the landing page here?   The landing page has a heading with the title Landing page.  Why isn’t it showing up?

The child pages will not render because one last step needs to be implemented. 

You need to import Outlet from react dom and add it to your layout page as a component.  This Outlet component ensures react renders all nested pages based on their respective path.   Layout.jsx now looks like:

Reviewing the Results

See my live demo site here: Vite + React (myreactrouternotes2.netlify.app)

My Landing Page:

That’s it for this blog.   It’s critically important to know why you might use nested pages in a react application.  

Code Sample for the above project is available here:   ReactHelp/React Router/pt2 at main · RussMaxwell/ReactHelp (github.com)

Thank You,

Russ Maxwell