Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Routes and route modules

A route connects a page address to the file that describes it. In framework mode all routes are listed in a single file, app/routes.ts, and each page file is called a route module.

The routes.ts file

A new project already has it with one route:

// app/routes.ts
import { type RouteConfig, index } from "@react-router/dev/routes";
 
export default [index("routes/home.tsx")] satisfies RouteConfig;

index sets the page for the root address /. The file path is relative to the app/ folder.

A new page

Add an "About" page. First create app/routes/about.tsx:

// app/routes/about.tsx
export default function About() {
  return <h1>About the blog</h1>;
}

Then register it with route(address, file):

// app/routes.ts
import { type RouteConfig, index, route } from "@react-router/dev/routes";
 
export default [
  index("routes/home.tsx"),
  route("about", "routes/about.tsx"),
] satisfies RouteConfig;

Open http://localhost:5173/about — the heading "About the blog" appears. The address is written without a leading slash. The file alone does nothing without an entry in routes.ts: the file name does not affect the address.

What a module exports

A route module is an ordinary TypeScript file where some exports have a special meaning:

ExportPurpose
defaultThe page component
loaderLoading data on the server
actionHandling a submitted form
metaTitle and meta tags
linksStylesheets and other link tags
ErrorBoundaryWhat to show on an error

Each one has its own lesson. For now the default component is enough.

Generated types

For every module the framework generates a types file. You import it from a sibling "folder" ./+types/file-name:

// app/routes/about.tsx
import type { Route } from "./+types/about";
 
export default function About(_props: Route.ComponentProps) {
  return <h1>About the blog</h1>;
}

Route.ComponentProps describes the page props: later it will contain loaderData and params with exact types. Types update by themselves while npm run dev is running; npx react-router typegen creates them manually.

Common mistake

The editor underlines import type { Route } from "./+types/about" with "module not found". The +types folder actually lives in .react-router/types and appears only after running npm run dev or npx react-router typegen. Run one of these commands and, if needed, restart TypeScript in your editor.

Thanks for reading!

Donate to the site — we work hard for you.