Sub topic 4
Navigating with Link and NavLink
This chapter assumes you can define routes with createBrowserRouter and render them with RouterProvider. It also assumes you know what a nested route is. Here you will learn how Link and NavLink move the user between those routes without reloading the page, how relative paths resolve, and how to style the current link.
Why not a plain anchor tag
An <a href="/about"> makes the browser request a new document from the server. React state is lost and the whole app boots again. Link renders a real <a> element, so it keeps the accessibility and right-click behavior of a link. It also intercepts ordinary left clicks, cancels the browser's default navigation, and asks the router to change the URL through the History API.
Link leaves some clicks to the browser. Ctrl-click, Cmd-click, middle-click, and links with target="_blank" still open a new tab, because the browser handles them with the real href.
Basic Link usage
The to prop takes a string or an object with pathname, search, and hash. Two optional props change how the navigation is recorded.
import { Link } from "react-router-dom";
function ProductCard({ product }) {
return (
<div>
<Link to={`/products/${product.id}`}>{product.name}</Link>
<Link to={{ pathname: "/products", search: "?sort=price", hash: "#top" }}>
Cheapest first
</Link>
<Link to="/login" replace state={{ from: "/cart" }}>
Sign in
</Link>
</div>
);
}replaceswaps the current history entry instead of adding one. The Back button then skips the page you left. This suits redirect-like flows such as a login screen.stateattaches a value to the history entry. The destination reads it withuseLocation().state. The value survives a reload in most browsers because it is stored in the history entry, but it isundefinedwhen someone opens the URL directly. Never depend on it for required data.
Absolute and relative paths
A to that starts with / is absolute and always resolves from the root of the app. A to without a leading slash is relative.
Relative links resolve against the route hierarchy, not against the current URL string. A link rendered by a route whose path is users/:userId and pointing to to="settings" goes to /users/42/settings. A link with to=".." goes to the parent route's path, one route level up, not one URL segment up.
import { Link } from "react-router-dom";
// Rendered by the route { path: "users/:userId", element: <User /> }
// when the URL is /users/42
function UserLinks() {
return (
<ul>
<li><Link to="settings">Settings</Link></li> {/* /users/42/settings */}
<li><Link to="..">All users</Link></li> {/* /users */}
<li><Link to=".." relative="path">Path up</Link></li> {/* /users */}
</ul>
);
}The last two links give the same result here, but they differ in general. With relative="path", .. removes one URL segment. Without it, .. removes one matched route. If a single route has the path users/:userId/posts, then .. jumps over both segments, while relative="path" removes only posts. Prefer the default, because relative links then keep working when you move or rename parent paths.
Styling the current page with NavLink
NavLink is a Link that knows whether its target matches the current location. Navigation menus are its main use. It adds the class active to a matching link and sets aria-current="page", which screen readers announce.
You can also compute the class yourself. className, style, and children each accept a function that receives a state object.
import { NavLink } from "react-router-dom";
function UserLink({ id }) {
return (
<NavLink
to={`/users/${id}`}
className={({ isActive, isPending }) =>
isActive ? "active" : isPending ? "pending" : undefined
}
>
{({ isActive }) => <span>{isActive ? "Viewing user " : "User "}{id}</span>}
</NavLink>
);
}| State | True when |
|---|---|
| `isActive` | The link's path matches the current URL |
| `isPending` | The user clicked this link and its route's loaders are still running |
| `isTransitioning` | A view transition is in progress, when you use the `viewTransition` prop |
isPending only works with a data router such as createBrowserRouter. In a data router, the pending state lets you show feedback on the link before the next page is ready.
Matching is by prefix, so use `end`
NavLink counts a link as active when the current URL starts with the link's path, aligned on segment boundaries. A link to /users is active at /users, /users/42, and /users/42/settings. Often that is what you want, since the Users tab should stay highlighted while the user views one profile.
Add end when only an exact match should count.
import { NavLink } from "react-router-dom";
function Tabs() {
return (
<nav>
<NavLink to="/" end>Home</NavLink>
<NavLink to="/users">Users</NavLink>
<NavLink to="/users/new" end>New user</NavLink>
</nav>
);
}Without end on /users, a link to /users would stay active at /users/new. Here /users/new has end, so it is active only at its own URL, but the Users link is still active there. If you want just one highlighted tab, put end on /users as well. The link to / is a special case. React Router treats it as exact automatically, so it is not active everywhere.
Other useful props
reloadDocumentmakes the link behave like a normal anchor and load a full page. Use it to leave the React app for a path the server renders, such as a downloadable file.preventScrollResetkeeps the scroll position after navigation when you use theScrollRestorationcomponent. Tab-style navigation often wants this.caseSensitiveonNavLinkmakes/Aboutnot match/about.
Common mistakes
- Link outside the router.
Linkneeds router context. If you render it in a component tree thatRouterProviderdoes not control, such as a separatecreateRootcall, you get an error saying<Link>may be used only in the context of a<Router>. In tests, wrap the component in a memory router. - Forgetting the leading slash.
to="about"rendered from a nested route points to a child of the current route, not to the top-level/about. If a link ends up at a doubled path like/users/about, check whether you meant/about. - Using Link for actions. A link should move to a page. For "delete" or "save", use a button with an event handler or a
Form, covered in later chapters. Navigation from code, such as after a successful save, is the topic of the programmatic navigation chapter. - Highlighting too many tabs. If several
NavLinks are active at once, you probably needend.
Exercise
Your layout has NavLinks to "/", "/users", and "/users/new". On /users/new, both "/users" and "/users/new" show the active style. Which change makes only "New user" look active, and why does "/" stay inactive without any change?
Show answer
Add the end prop to the "/users" NavLink. By default NavLink matches by path prefix, so "/users" is active on every URL that starts with "/users", including "/users/new". With end, it matches only "/users" exactly. The "/" link is inactive because React Router automatically treats a link to the root path as an exact match.