π Client-Side Navigation (No Reload)
In React Router:
Navigation does not reload the page
Only the URL changes
React updates the UI instantly
β Traditional navigation (<a href="">)
Triggers full page reload
Loses state
β React Router navigation
Fast
Smooth
SPA-friendly
π What Is <Link>?
Used to navigate between routes
Replaces
<a>tags in React appsPrevents page reload
Example
<Link to="/">Home</Link>
<Link to="/contact">Contact</Link>π Always use Link for internal navigation.
π§ What Is <NavLink>?
Special version of
LinkKnows whether the route is active
Used for navigation menus
Basic Syntax
<NavLink to="/about">About</NavLink>π¨ Active Link Styling
Using className Function
<NavLink
to="/about"
className={({ isActive }) =>
isActive ? 'active-link' : 'link'
}
>
About
</NavLink>Example CSS
.link {
color: black;
text-decoration: none;
}
.active-link {
color: blue;
font-weight: bold;
}π isActive becomes true when the route matches the URL.
π What Is useNavigate()?
A hook used for programmatic navigation
Useful for:
Button clicks
Form submissions
Redirects after login
Basic Syntax
const navigate = useNavigate();
navigate('/dashboard');Example: Button Navigation
import { useNavigate } from 'react-router-dom';
function LoginButton() {
const navigate = useNavigate();
return (
<button onClick={() => navigate('/profile')}>
Go to Profile
</button>
);
}Go Back / Forward
navigate(-1); // back
navigate(1); // forwardπ οΈ Hands-On: Navbar with Active States
src/components/Navbar.jsx
import { NavLink } from 'react-router-dom';
function Navbar() {
return (
<nav>
<NavLink to="/" end>Home</NavLink>
<NavLink to="/about">About</NavLink>
<NavLink to="/contact">Contact</NavLink>
</nav>
);
}
export default Navbar;π end ensures / matches only the home route.
π Hands-On: Button-Based Navigation
import { useNavigate } from 'react-router-dom';
function ContactButton() {
const navigate = useNavigate();
return (
<button onClick={() => navigate('/contact')}>
Contact Us
</button>
);
}
export default ContactButton;π§ Common Mistakes
β Using
<a href>instead ofLinkβ Forgetting
endon homeNavLinkβ Trying to use
useNavigateoutside Routerβ Hard-refreshing after navigation
β When to Use What?
Use Case | Recommended |
|---|---|
Simple navigation |
|
Menu with active state |
|
Button / logic-based navigation |
|