Greetings, fellow coders! Our mission today involves Nested Routing in React and the protection of secret paths using react-router-dom v6. We aim to master Nested Routes and Protected Routes in our React application!
We will:
- Discover Nested Routing.
- Set up routes using
Outlet. - Guard routes with the
element. - Explore other routes using
Navigate.
Let's embark on this journey!
Nested Routing involves defining a route within another — much like a set of Russian dolls. It's especially useful when building complex React applications.
Imagine creating a space travel blog. The homepage lists all the visited planets, and clicking a planet takes you to a “planet” page that shows various posts about your visit. These posts can then be further categorized, creating a nested route for easier navigation.
To guide our spaceship to nested voyages, we set up Nested Routes using the Outlet component in react-router-dom v6. The Outlet component acts as a placeholder for nested routes, like a docking bay where our spaceship can anchor when we travel within nested sections of our journey.
Let's say we're creating a user profile page with 'Account Details' and 'Account Settings' pages accessible from there. So, we'll create nested routes under the 'Profile' route.
But what if we want to display a specific view when users visit the 'Profile' route initially, like a 'Profile Overview' page? Here's where the index attribute comes in!
The index attribute in react-router-dom v6 allows us to set a default nested route that will be displayed when the parent route is visited. Wrapping the ProfileOverview component with the Route component and including the index attribute will set this as the default view for the 'Profile' route.
Here is an updated example:
Here, visiting '/profile' will display the ProfileOverview. If the user navigates to '/profile/details' or '/profile/settings', the respective components will be rendered.
