Links and navigation
To move between pages without a full reload, use components from react-router instead of the a tag. The framework then loads the new page's data itself and puts the page into the layout. The components are the same as in library mode, but here they have a couple of extra features.
Link
Add a menu to the layout app/routes/layout.tsx:
// app/routes/layout.tsx
import { Link, Outlet } from "react-router";
export default function Layout() {
return (
<>
<header>
<Link to="/">Posts</Link> <Link to="/about">About</Link>
</header>
<main>
<Outlet />
</main>
</>
);
}Clicking "About" changes the address to /about and shows the page while the header stays in place. In HTML it is an ordinary a href link, so it works even before JavaScript loads.
NavLink
NavLink is a link that knows whether it is active. You can pass a function to className:
// app/routes/layout.tsx
import { NavLink } from "react-router";
<NavLink to="/about" className={({ isActive }) => (isActive ? "active" : "")}>
About
</NavLink>While /about is open, the link gets the active class, and you can highlight it with styles. Without a function NavLink adds the active class on its own. For a link to / add the end prop, otherwise it is active on every page.
Prefetching
In framework mode a link can load a page's code and data in advance:
// app/routes/home.tsx
<Link to="/about" prefetch="intent">About</Link>prefetch value | When to load |
|---|---|
none | Never (default) |
intent | On hover or focus |
render | As soon as the link renders |
viewport | When the link is visible on screen |
With intent navigation feels instant: while the user was moving the pointer, the data already arrived.
useNavigate
Sometimes you need to navigate from code — for example, from a "Back" button or a timer:
// app/routes/about.tsx
import { useNavigate } from "react-router";
export default function About() {
const navigate = useNavigate();
return (
<>
<h1>About the blog</h1>
<button onClick={() => navigate(-1)}>Back</button>
<button onClick={() => navigate("/")}>Home</button>
</>
);
}navigate(-1) goes back one page in history, navigate("/") opens the home page.
Common mistake
People use useNavigate to redirect after a form submission or after checking whether the user is logged in. In framework mode that happens on the server: an action or loader returns redirect("/...") (covered in the lessons on actions and authentication). For ordinary click navigation choose Link: search engines can follow it, and it works even before JavaScript loads.