Link
In React Router, the Link
component is used to create navigation links that allow users to navigate between different routes in a single-page application (SPA). Instead of performing a full page reload, the Link
component allows React to handle navigation internally, ensuring fast transitions and preserving the app’s state.
Key Features of Link
:
- Client-Side Navigation: When clicked,
Link
updates the browser’s URL without reloading the entire page, enabling smooth transitions between routes. - Declarative Navigation: Instead of using
<a>
tags, which perform a full page refresh,Link
provides a declarative way to define navigation between routes in your app. - Preserves State: Since the page isn’t reloaded, your app’s state (data in memory, forms, etc.) remains intact between navigations.
Basic Usage:
Here’s a simple example of how to use Link
in a React Router app:
import { Link } from "react-router-dom";
function Navbar() {
return (
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
);
}
export default Navbar;
In this example:
- The
to
attribute inLink
specifies the route (or URL path) to navigate to. - When a user clicks on one of these links, React Router changes the route without reloading the page.
Advanced Usage:
You can also pass more advanced configurations, such as query parameters, URL fragments, or even objects in the to
attribute.
<Link
to={{
pathname: "/profile",
search: "?id=123", // Adds query params
hash: "#details", // Adds URL fragment
state: { fromDashboard: true } // Passes state to the route
}}
>
Profile
</Link>
Important Points:
- No Full Reload: Unlike a regular
<a>
tag, which triggers a full page reload,Link
allows for navigation within the SPA, making the app feel faster and more fluid. - SEO: Even though
Link
doesn’t trigger a full page reload, the URL is updated in the browser, so users can bookmark or share links, and search engines can still crawl your app if properly configured with server-side rendering or static generation. - Accessibility:
Link
behaves like a normal anchor tag in terms of accessibility (for screen readers and keyboard navigation), so it’s an accessible solution for navigating SPAs.
Example Application:
import React from "react";
import { BrowserRouter as Router, Route, Link, Routes } from "react-router-dom";
function App() {
return (
<Router>
<div>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
</Router>
);
}
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
export default App;
Summary:
Link
is a core part of React Router used to navigate between routes in SPAs.- It ensures smooth navigation without a full page reload, improving performance and user experience.
- The
to
prop inLink
can accept a string (for basic paths) or an object (for advanced routing options like query params or state).
This makes it a critical component for building navigation in modern React applications.
In React Router, NavLink
is a specialized version of the Link
component used for navigation. The main difference is that NavLink
allows you to style or apply a class to the link when it matches the current route, making it useful for creating active navigation links (like highlighting the active page in a navbar).
Key Features of NavLink
:
- Active State:
NavLink
automatically applies an “active” style or class when the link’s destination matches the current URL. This is especially useful for navigation menus, where you want to visually indicate which page is currently active. - Custom Styling: You can apply custom styles or classes based on whether the link is active or inactive, allowing for a more dynamic user experience.
- Exact Matching: You can use the
end
prop to ensure thatNavLink
matches the exact URL path and doesn’t partially match sub-paths.
Example Usage:
Here’s a simple example of how to use NavLink
in a React app:
import { NavLink } from "react-router-dom";
function Navbar() {
return (
<nav>
<ul>
<li>
<NavLink
to="/"
end // Ensures exact matching for the home route
style={({ isActive }) => ({
color: isActive ? "green" : "blue" // Active link is green, inactive is blue
})}
>
Home
</NavLink>
</li>
<li>
<NavLink
to="/about"
style={({ isActive }) => ({
color: isActive ? "green" : "blue"
})}
>
About
</NavLink>
</li>
<li>
<NavLink
to="/contact"
className={({ isActive }) => (isActive ? "active-link" : "")} // Apply "active-link" class to active link
>
Contact
</NavLink>
</li>
</ul>
</nav>
);
}
export default Navbar;
Explanation:
- Active Styling: In the
NavLink
, you can dynamically change the style or class based on whether the link is active (viaisActive
). - Exact Matching (
end
prop): When theend
prop is added, theNavLink
will only be considered active if the URL exactly matches theto
prop. This prevents partial matches (e.g.,/
also matching/about
).
Props for NavLink
:
to
: The URL path to navigate to (similar toLink
).style
orclassName
: These can be functions that accept theisActive
flag to apply dynamic styles or classes to the link.end
: Ensures exact matching for routes like/
, where partial matching might otherwise occur.state
,replace
,reloadDocument
: Additional props inherited fromLink
for handling navigation behavior.
Why Use NavLink
?
- Visual Feedback: It provides immediate visual feedback to the user about which route is currently active, improving the navigation experience.
- Customization: You can easily style active links differently (e.g., changing colors, adding underlines) without manually managing the active state.
Example with Custom Class:
<NavLink
to="/dashboard"
className={({ isActive }) => (isActive ? "active-dashboard" : "inactive-dashboard")}
/>
In this example, when the /dashboard
route is active, the link will receive the active-dashboard
class. Otherwise, it will receive inactive-dashboard
.
Summary:
NavLink
is an enhanced version ofLink
that provides an easy way to manage active/inactive states of links.- It’s especially useful for creating navigational elements like menus, where you want to highlight or style the active route.
- You can customize the appearance of
NavLink
based on whether it matches the current route, improving the user interface and navigation experience.
It’s a powerful tool for creating intuitive and visually dynamic navigation in React Router applications.
In React Router, the relative='path'
option for the Link
component allows you to define whether a path is relative to the current route. By default, React Router interprets paths in Link
as absolute, meaning they will resolve from the root of the app. However, if you set relative="path"
, the navigation will be relative to the current route, enabling more dynamic routing based on where the link is located within the route structure.
Example:
<Link to="profile" relative="path">Profile</Link>
This link will resolve based on the current route.
In React Router, setting relative="route"
in a Link
component allows the path to be resolved based on the current route’s context rather than the root. This is particularly useful for nested routes, where the link adapts according to the parent route’s path.
Example:
<Link to="settings" relative="route">Settings</Link>
This link will navigate to the settings
page relative to the current route, maintaining the proper URL structure within nested routes.
Use the share button below if you liked it.
It makes me smile, when I see it.