Topic 37 of 54
Linking Between Pages
Overview
As mentioned, you cannot use standard HTML `<a>` tags for internal links, because they trigger a full browser reload. Instead, `react-router-dom` provides a `<Link>` component. It looks and acts like an `<a>` tag to the user and to search engines, but it intercepts the click event to perform client-side routing instead.
Syntax
Behind the scenes, `<Link>` renders an `<a>` tag, but it adds an `onClick` handler that calls `e.preventDefault()` and pushes the new URL to the browser's history API.
The <Link> Component
jsx
import { Link } from 'react-router-dom';
function Navigation() {
return (
<nav>
{/* Use 'to' instead of 'href' */}
<Link to="/">Home</Link>
<Link to="/about">About Us</Link>
{/* You can still use standard <a> tags for EXTERNAL links! */}
<a href="https://google.com" target="_blank">Search</a>
</nav>
);
}`<NavLink>` is a special version of `<Link>` specifically designed for navigation menus. It knows when it is 'active' based on the current URL, allowing you to easily style it differently.
For Active
jsx
import { NavLink } from 'react-router-dom';
function Sidebar() {
return (
<nav>
{/* NavLink automatically gets an 'active' class when its URL matches */}
<NavLink
to="/dashboard"
className={({ isActive }) => isActive ? "active-link" : ""}
>
Dashboard
</NavLink>
</nav>
);
}Common Pitfalls
- Using `<Link>` for external URLs (like linking to Facebook). It will try to route to `localhost:3000/https://facebook.com` and fail.
Interview Tips
- Always know the difference between `<Link>` (standard navigation) and `<NavLink>` (navigation that needs styling when active).
Real-World Example
Passing data 'invisibly' through a Link using the `state` prop.
example
jsx
function ProductList() {
return (
<Link
to="/checkout"
state={{ fromCart: true, total: 50.00 }}
>
Go to Checkout
</Link>
);
}
// On the Checkout page, you can retrieve this using the useLocation hook:
// const location = useLocation();
// console.log(location.state.total); // 50.00