TanStack Router (or React Router)
All information mentioned in Pages & Routes (Common Concepts) applies.
In TanStack Router (or React Router) applications, organize route files following the file-based routing pattern:
- Routes Directory
Create route files directly in the routes directory (e.g.,routes/_Layout/posts/index.tsx). - Route Loaders
Keep route-specific data fetching logic in the route file usingloaderfunctions.
Example Structure
Section titled “Example Structure”Directorysrc/
Directorycomponents/
Directoryui/
- Card.tsx # Shared UI component
Directoryapp/ # Application configuration
- Providers.tsx # Global providers (RouterProvider, etc.)
- router.tsx # TanStack Router configuration
- routes.ts # Route constants and type definitions
Directoryroutes/
- __root.tsx # Root route component
- _Layout.tsx # Main layout route
Directory_Layout/ # Nested routes under main layout
Directoryposts/
- index.tsx # Route definition of posts feature with loader and component
Directorysearch/
- index.tsx # Route definition of search feature with component
- login.tsx # Login page route
Directoryfeatures/
Directoryposts/
Directoryapi/ # Query keys and query options for posts API calls
- …
Directorycomponents/ # Posts-specific components
- PostList.tsx # Posts list component
- PostListItem.tsx # Posts list item component
Directoryhooks/ # Posts-specific hooks
- …
Directorysearch/
Directoryapi/ # Query keys and query options for search API calls
- …
Directorycomponents/ # Search-specific components
- SearchList.tsx # Search list component
Directoryhooks/ # Search-specific hooks
- …
Directorylib/
- PostListItemContext.tsx
Example Route
Section titled “Example Route”export const Route = createFileRoute("/_Layout/posts")({ component: PostPage, loader: ({ context: { queryClient } }) => { void queryClient.prefetchQuery(postListQueryOptions()); },});
function PostPage() { const { t } = useTranslation("posts");
return ( <Card> <Card.Header> <Typography type="display-4xl">{t("title")}</Typography> </Card.Header> <Card.Content> <PostList /> </Card.Content> </Card> );}