Sub topic 2
Navigating with Link and NavLink
Assume you know React components, TypeScript, HTTP requests, and HTML forms. This chapter connects navigation to server data loading and mutations in React Router framework mode.
Navigating with Link and NavLink
Use Link for client-side navigation without a full browser reload. Use NavLink when the link needs an active style or label.
import { Link, NavLink } from "react-router";
export default function Navigation() {
return (
<nav>
<NavLink
to="/contacts"
className={({ isActive }) => (isActive ? "active" : undefined)}
>
Contacts
</NavLink>
<Link to="/contacts/new">Add contact</Link>
</nav>
);
}A client-side navigation matches the next route, runs its loader on the server, and renders the returned data.
Loaders and generated route types
A loader reads data before the route component renders. React Router generates types from the route module, so Route.ComponentProps types loaderData and actionData.
import { Form, data, redirect } from "react-router";
import type { Route } from "./+types/contacts";
import { getContacts, createContact } from "~/contacts.server";
export async function loader() {
return { contacts: await getContacts() };
}
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData();
const name = String(formData.get("name") ?? "").trim();
if (!name) {
return data({ error: "Name is required" }, { status: 400 });
}
const contact = await createContact({ name });
return redirect(`/contacts/${contact.id}`);
}
export default function Contacts({
loaderData,
actionData,
}: Route.ComponentProps) {
return (
<>
<ul>
{loaderData.contacts.map((contact) => (
<li key={contact.id}>{contact.name}</li>
))}
</ul>
<Form method="post">
<input name="name" />
{actionData?.error ? <p role="alert">{actionData.error}</p> : null}
<button type="submit">Create</button>
</Form>
</>
);
}Server boundaries, actions, and validation
Files ending in .server.ts contain server-only code, such as database queries. Importing them from a route loader or action keeps those operations on the server. The browser receives only the loader result.
A Form submits to the current route's action. The action validates input, returns a 400 response when validation fails, or redirects after success. Returning an error preserves the form page so the component can display feedback.
Exercise
Why should a database helper live in a .server.ts file instead of a normal utility file?
Show answer
The .server.ts suffix marks it as server-only, preventing database code and credentials from being included in the browser bundle.