Routing in web development is essential to create a
seamless user experience by navigating through different pages or views. React,
with the help of libraries like react-router, provides a powerful way to handle
routing within Single Page Applications (SPAs). One of the key features of
React routing is nested routes, which allow you to render components within
other components.
What is a Nested Route?
A nested route in React refers to a route that exists inside another route. Instead of all components being loaded at the same level (like a flat structure), you can create parent-child relationships between routes, where one route is rendered inside another.
For example, let’s say you have a parent route /dashboard and a nested route /dashboard/settings. The settings component will be displayed within the dashboard component, preserving the context of the dashboard while allowing the user to interact with different sections.
Let’s implement nensted routes for a university website, where the main route is /university and there are three nested routes.
· /university/about
· /university/alumni
· /university/news
We can model nested routes like below.
<BrowserRouter> <Routes> <Route path="/" element={<University />} /> <Route path="/university" element={<University />}> <Route path="about" element={<About />} /> <Route path="alumni" element={<Alumni />} /> <Route path="news" element={<News />} /> </Route> </Routes> </BrowserRouter>
There are three nested routes inside the /university route.
<Route path="about" element={<About />} />
<Route path="alumni" element={<Alumni />} />
<Route path="news" element={<News />} />
path="about": This means when the user visits /university/about, the About component will be shown inside the University component.
path="alumni": When the user visits /university/alumni, the Alumni component will be shown inside University.
path="news": When the user visits /university/news, the News component will be shown inside University.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘nested-routes-demo’.
Project structure looks like below.
Step 2: Navigate to the project directory and install react router dom by executing below commands.
cd nested-routes-demo npm install react-router-dom
Step 3: Create pages folder in src folder and define following pages in pages folder.
University.jsx
import { Outlet, Link } from "react-router-dom";
import "../styles.css";
export default function University() {
return (
<>
<nav className="menu">
<ul>
<li>
<Link to="/university/about">About</Link>
</li>
<li>
<Link to="/university/alumni">Alumni</Link>
</li>
<li>
<Link to="/university/news">News</Link>
</li>
</ul>
</nav>
<h1>ABC Autonomous University</h1>
<p>
Welcome to ABC University, a place where tradition meets innovation.
Since our founding in 1901, we have been committed to academic
excellence, fostering a diverse and inclusive community, and preparing
students to lead and make a difference in the world.
</p>
<Outlet />
</>
);
}
It <Outlet> component serves as a placeholder for rendering child routes within a parent route component. Think of it as a placeholder where child components will be inserted when their routes are matched. It acts like a window through which nested routes can be displayed within a parent component.
About.jsx
export default function About() {
return (
<>
<h1>About us</h1>
<p>
Welcome to ABC University, where we believe in the power of education to
transform lives and communities. Established in 1901, ABC University has
grown to become a leading institution known for its commitment to
academic excellence, innovation, and inclusivity.
</p>
</>
);
}
Alumni.jsx
export default function Alumni() {
return (
<>
<h1>Alumni</h1>
<p>
The ABC University Alumni Network is a vibrant community of over 100,000
graduates who are making waves across various industries worldwide. Our
alumni are leaders, innovators, and change-makers who continue to
contribute to society in impactful ways.
</p>
</>
);
}
News.jsx
export default function News() {
return (
<>
<h1>Recent News Highlights</h1>
<ul>
<li>
<h3>ABC University Launches Sustainability Initiative</h3>
<p>
ABC University has unveiled a new campus-wide sustainability program
aimed at reducing the university’s carbon footprint by 50% over the
next decade. As part of this initiative, solar panels have been
installed across campus, and new eco-friendly policies have been
implemented.
</p>
</li>
<li>
{" "}
<h3>ABC Students Win National Innovation Award</h3>
<p>
A team of engineering students from ABC University recently won
first place at the National Innovation Challenge for their
cutting-edge technology designed to improve water purification in
developing countries.
</p>
</li>
</ul>
</>
);
}
Step 4: Create styles.css file in src folder.
styles.css
/* Menu container */
.menu {
background-color: lightgray;
padding: 10px;
}
/* Menu list - removes bullets and adds horizontal display */
.menu ul {
display: flex; /* Use flexbox for layout */
list-style-type: none; /* Remove default list styling */
padding: 0; /* Remove default padding */
margin: 0; /* Remove default margin */
justify-content: space-around; /* Distribute items evenly with space between */
background-color: #f8f8f8; /* Light background color */
border-radius: 20px; /* Rounded corners */
box-shadow: 0 3px 5px rgba(0, 0, 0, 0.1); /* Subtle shadow for depth */
}
/* Menu items */
.menu ul li {
padding: 10px 20px;
color: white;
cursor: pointer;
text-align: center;
}
/* Hover effect for menu items */
.menu ul li:hover {
background-color: #575757;
}
/* Optional: Add some spacing between the menu items */
.menu ul li + li {
margin-left: 15px;
}
Step 5: Update App.jsx with below content.
App.jsx
import University from "./pages/University";
import About from "./pages/About";
import Alumni from "./pages/Alumni";
import News from "./pages/News";
import { BrowserRouter, Routes, Route } from "react-router-dom";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<University />} />
<Route path="/university" element={<University />}>
<Route path="about" element={<About />} />
<Route path="alumni" element={<Alumni />} />
<Route path="news" element={<News />} />
</Route>
</Routes>
</BrowserRouter>
);
}
export default App;
Step 6: Update main.jsx with below content.
main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
)
Step 7: Build and run the application by executing below commands.
cd nested-routes-demo npm install npm run dev
Open the url http://localhost:5173/ in browser, you will see below kind of screen,
Click on ‘About’ page, you will be taken to About page content.
As you observe above screen, the content of About us is rendered at Outlet section of Dashboard component.
You can download the application from this link.
Previous Next Home
No comments:
Post a Comment