In React, routing is handled by libraries like react-router-dom, which allows you to create single-page applications (SPAs) with seamless navigation between different components or views. Two commonly used components for navigation are <Link> and <NavLink>. These components enable users to navigate between routes without a full page reload, providing a smooth user experience.
1. <Link> Component
The <Link> component is used to create a hyperlink to a specific route within the application. It replaces the traditional HTML <a> tag for internal navigation to prevent full page reloads.
Key Features
Client-Side Navigation: It allows for navigation without reloading the page, keeping the application fast and efficient.
Example
<Link to="/about">Go to About Page</Link>
In this snippet, clicking the "Go to About Page" link will navigate the user to the /about route without reloading the page.
2. <NavLink> Component
The <NavLink> component extends <Link> with additional features specifically designed for navigation menus or navigation bars. It allows you to apply active styles or classes based on the current route, making it ideal for indicating which route is currently active.
Key Features
Active Styling: The most important feature of <NavLink> is the activeClassName or activeStyle prop, which allows you to automatically apply styles when the link's route matches the current URL.
Exact Matching: The exact prop ensures that the active styles are applied only when the URL exactly matches the to prop.
Example
<NavLink to="/about/college" exact activeClassName="active">
The About link (with exact) will be active for /about/college (exact matching).
With exact ensures that the link only matches the exact path. This is useful when you want a clear distinction between pages and sub-pages.
<NavLink to="/about/college" activeClassName="active">
The About link (without exact) will be active for /about, /about/college.
Without exact: Routes with similar prefixes, like /about/college, will match additional paths like /about as well. This is fine for menus where you want to keep the "About" link highlighted even when you're on sub-pages.
Let’s build an application to understand this concept better.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘navlink-demo’.
Project structure looks like below.
Step 2: Install react router dependency.
To implement routing, we need to install the react-router-dom package. This will allow us to use React Router for navigation.
Go to the project root folder and execute below command.
Step 2: Install react router dependency.
To implement routing, we need to install the react-router-dom package. This will allow us to use React Router for navigation.
Go to the project root folder and execute below command.
npm install react-router-dom
Step 3: Create pages folder in src folder define the components HomePage, AboutPage, SportsPage, and AcademicsPage.
HomePage.jsx
export default function HomePage() { return ( <> <h3>Home</h3> <p> At ABC Enginneering College, we are committed to nurturing the next generation of engineers who will innovate and lead the future. With a strong focus on academic excellence, cutting-edge research, and holistic development, our institution is a hub for ambitious minds ready to make an impact in the world. </p> </> ); }
AboutPage.jsx
export default function AboutPage() { return ( <> <h3>About</h3> <p> Established in 1965, ABC Engineering has been a beacon of academic excellence and innovation in engineering education. Our mission is to equip students with the skills, knowledge, and ethical grounding to become leaders in the global engineering landscape. With a strong focus on both theoretical foundations and practical applications, we foster a learning environment that encourages creativity, critical thinking, and collaboration. Over the years, we have built a reputation for producing graduates who excel in diverse industries and contribute meaningfully to technological advancements. </p> </> ); }
SportsPage.jsx
export default function SportsPage() { return ( <> <h3>Sports</h3> <p> At ABC Engineering, we believe that physical fitness and teamwork are just as important as academic achievement. Our vibrant sports culture offers students a range of opportunities to engage in both competitive and recreational activities. Whether it's cricket, football, basketball, volleyball, or athletics, our state-of-the-art sports facilities and well-maintained grounds provide the perfect environment for athletes to thrive. Regular tournaments, inter-college competitions, and intramural leagues help foster a spirit of sportsmanship, camaraderie, and leadership among students. We encourage every student to participate and embrace a balanced, healthy lifestyle. </p> </> ); }
CollegePage.jsx
export default function CollegePage() {
return (
<>
<h3>College Overview</h3>
<p>
With 10 dynamic departments, 150+ experienced faculty members, and a
thriving student community of over 3,000, [Your College Name] is
dedicated to fostering academic excellence and innovation. Our strong
focus on employability has resulted in an impressive 95% campus
placement rate each year, with students securing positions in leading
national and international companies. Spread over 50 acres of modern
infrastructure, the campus is designed to provide an exceptional
learning experience, combining academics, research, and extracurricular
activities.
</p>
</>
);
}
Step 4: Create styles.css in src folder.
styles.css
.active{
text-decoration: none;
color: #333;
font-size: 16px;
display: inline-block;
transition: color 0.3s ease, background-color 0.3s ease;
background-color: #f0f0f0;
color: #007bff;
}
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 */
}
li {
padding: 10px 15px; /* Add padding for clickable area */
}
Step 5: Update App.jsx with below content.
App.jsx
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
import { NavLink } from "react-router-dom";
import AboutPage from "./pages/AboutPage";
import CollegePage from "./pages/CollegePage";
import HomePage from "./pages/HomePage";
import SportsPage from "./pages/SportsPage";
import "./styles.css";
function Navbar() {
return (
<nav>
<ul>
<li>
{/* Exact matching */}
<NavLink to="/" exact activeClassName="active">
Home
</NavLink>
</li>
<li>
{/* Non-exact matching */}
<NavLink to="/about" activeClassName="active">
About
</NavLink>
</li>
<li>
{/* Another link under "/about" */}
<NavLink to="/about/college" activeClassName="active">
College
</NavLink>
</li>
<li>
<NavLink to="sports" activeClassName="active">
Sports
</NavLink>
</li>
</ul>
</nav>
);
}
function App() {
return (
<>
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="/about/college" element={<CollegePage />} />
<Route path="/sports" element={<SportsPage />} />
</Routes>
<footer>
<p>© 2024 ABC Engineering. All rights reserved.</p>
</footer>
</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 navlink-demo npm install npm run dev
Open the url 'http://localhost:5173/' in browser, you can see the below screen. Just observe the scree, only Home link is highlighted with blue color. There is no change in rest of the menus.
Click on About link, you can observe About link is highlighted.
Now let’s click on college link, you can observe that bout About and College are highlighted in blue color.
You can download this application from this link.
No comments:
Post a Comment