Sub topic 6
Navigating with Link and NavLink
This chapter assumes you can write React components and TypeScript. It also assumes you have defined routes in app/routes.ts and understand nested routes with Outlet. You should know the HTTP basics behind a normal link click.
Why not use a plain anchor?
A plain <a href="/contacts"> makes the browser request a whole new HTML document. The page reloads, React state is lost, and every script runs again.
In framework mode, Link and NavLink render an <a> element but intercept the click. React Router then changes the URL with the History API. It calls only the loaders for routes that are new or have changed, and it re-renders the matched route modules. The document stays loaded, so state in unaffected layouts is preserved.
The rendered output is still a real anchor with a real href. Right-click, "open in new tab", and crawlers all work. With server rendering, links also work before JavaScript loads, because the browser follows the href normally.
Link
Link takes a to prop. Import it from react-router.
import { Link } from "react-router";
export default function Home() {
return (
<nav>
<Link to="/contacts">All contacts</Link>
<Link to="/contacts/new">New contact</Link>
<Link to="/contacts/42">Contact 42</Link>
</nav>
);
}Absolute and relative paths
A to value starting with / is absolute. Any other value is relative to the route that renders the link, not to the current URL. This differs from a plain <a>.
| `to` value | Rendered inside route `contacts/:contactId` | Result |
|---|---|---|
| `"/contacts"` | any | `/contacts` |
| `"edit"` | `/contacts/42` | `/contacts/42/edit` |
| `".."` | `/contacts/42` | `/contacts` |
| `"?sort=name"` | `/contacts` | `/contacts?sort=name` |
".." goes up one route level. It does not go up one URL segment. If a route path has several segments, such as contacts/:contactId, ".." removes all of them. Use relative="path" when you want segment-based behavior:
import { Link } from "react-router";
export function BackLinks() {
return (
<>
<Link to="..">Up one route</Link>
<Link to=".." relative="path">
Up one URL segment
</Link>
</>
);
}Search params and objects
to can also be an object with pathname, search, and hash. Build query strings with URLSearchParams instead of concatenating strings, so values are encoded.
import { Link } from "react-router";
export function SearchLink({ term }: { term: string }) {
const search = new URLSearchParams({ q: term }).toString();
return <Link to={{ pathname: "/contacts", search }}>Search "{term}"</Link>;
}Useful props
replaceswaps the current history entry instead of adding one. Use it for redirect-like steps where Back should skip the page.stateattaches data to the history entry. It is readable withuseLocation, but it is lost when the user opens the link in a new tab.reloadDocumentmakes the link behave like a plain anchor, with a full page load. Use it to reach a non-React-Router page on the same host.prefetchloads data and modules ahead of the click. See the next section.
Prefetching
By default, nothing is fetched until the click. In framework mode, prefetch can start work earlier.
| Value | Behavior |
|---|---|
| `"none"` | Default. No prefetching. |
| `"intent"` | Prefetch on hover or focus. |
| `"render"` | Prefetch as soon as the link renders. |
| `"viewport"` | Prefetch when the link scrolls into view. |
import { Link } from "react-router";
export function ContactRow({ id, name }: { id: string; name: string }) {
return (
<Link to={`/contacts/${id}`} prefetch="intent">
{name}
</Link>
);
}Prefetching fetches the route's JavaScript module and the data from its loader, and it adds <link rel="prefetch"> tags to the page. "intent" is a good default for lists. "render" and "viewport" can create many requests, which costs server load, so use them sparingly.
NavLink
NavLink is a Link that knows whether its target matches the current URL. Use it for menus and tabs.
When the link matches, React Router adds the class active and the attribute aria-current="page". It also adds the class pending while the destination's loaders are running. You can style these with CSS, or use the render-prop forms of className, style, and children.
import { NavLink } from "react-router";
export function MainNav() {
return (
<nav>
<NavLink to="/" end>
Home
</NavLink>
<NavLink
to="/contacts"
className={({ isActive, isPending }) =>
isActive ? "nav-active" : isPending ? "nav-pending" : ""
}
>
{({ isPending }) => (isPending ? "Contacts..." : "Contacts")}
</NavLink>
</nav>
);
}The `end` prop
Matching is by prefix. to="/contacts" is active for /contacts and for /contacts/42, which is usually what you want for a section. The link to="/" would be active on every page, so give it end. With end, the link is active only when the URL matches exactly.
Pending state and navigation
isPending is true while the navigation to that link's destination is in flight. This gives instant feedback on slow loaders without extra state. For page-wide indicators, use useNavigation, covered in a later chapter.
Common errors
- Using
<a>for internal links. It works, but causes full page loads and loses client state. UseLink. - Using
Linkfor external URLs.to="https://example.com"is treated as external and rendered as a normal anchor, but a plain<a>states the intent more clearly. - Forgetting
endon the home link. The home item looks active everywhere. - Expecting relative links to follow the URL. They follow the route hierarchy. Check the
relativeprop when the result looks wrong. - Navigating for a mutation. A link sends a GET request. Anything that changes data should be a
Formwith an action, covered in the next chapters.
Exercise
A sidebar has <NavLink to="/contacts">Contacts</NavLink> and <NavLink to="/">Home</NavLink>. On /contacts/42, both links show as active. What change fixes Home, and why does Contacts stay active?
Show answer
Add end to the Home link: <NavLink to="/" end>. NavLink matches by path prefix, and / is a prefix of every URL, so without end it is always active. Contacts remains active on /contacts/42 because /contacts is a prefix of that URL, which is the desired behavior for a section link. Add end to Contacts only if you want it active on the list page alone.
Exercise
You render <Link to=".."> inside the route contacts/:contactId, shown at /contacts/42. Where does it go, and how do you make it go to /contacts/ segment-wise instead of route-wise if the route were defined as contacts/:contactId/edit and you wanted only one segment removed?
Show answer
Relative links follow the route hierarchy, so ".." goes to the parent route's URL. For a route defined with several segments, ".." removes all of that route's segments. Add relative="path", as in <Link to=".." relative="path">, to remove one URL segment at a time.