### Kitchen Sink Solid Query Setup Source: https://tanstack.com/router/latest/docs/framework/solid/examples/kitchen-sink-solid-query Initializes TanStack Router and Solid Query with route definitions, query options, and mutation hooks. ```typescript /* eslint-disable @typescript-eslint/no-unnecessary-condition */ import * as Solid from 'solid-js' import { render } from 'solid-js/web' import { ErrorComponent, Link, MatchRoute, Outlet, RouterProvider, createRootRouteWithContext, createRoute, createRouter, lazyRouteComponent, redirect, retainSearchParams, useNavigate, useRouter, useRouterState, useSearch, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import { QueryClient, QueryClientProvider, queryOptions, useMutation, useQuery, } from '@tanstack/solid-query' import { SolidQueryDevtools } from '@tanstack/solid-query-devtools' import { z } from 'zod' import { fetchInvoiceById, fetchInvoices, fetchUserById, fetchUsers, patchInvoice, postInvoice, } from './mockTodos' import type { Invoice } from './mockTodos' import './styles.css' // type UsersViewSortBy = 'name' | 'id' | 'email' const invoicesQueryOptions = () => queryOptions({ queryKey: ['invoices'], queryFn: () => fetchInvoices(), }) const invoiceQueryOptions = (invoiceId: number) => queryOptions({ queryKey: ['invoices', invoiceId], queryFn: () => fetchInvoiceById(invoiceId), }) const usersQueryOptions = ({ filterBy, sortBy, }: { filterBy?: string sortBy?: UsersViewSortBy }) => queryOptions({ queryKey: ['users', { filterBy, sortBy }], queryFn: () => fetchUsers({ filterBy, sortBy, }), }) const userQueryOptions = (userId: number) => queryOptions({ queryKey: ['users', userId], queryFn: async () => { const user = await fetchUserById(userId) if (!user) { throw new Error('User not found.') } return user }, }) const useCreateInvoiceMutation = () => { return useMutation(() => ({ mutationKey: ['invoices', 'create'], mutationFn: postInvoice, onSuccess: () => queryClient.invalidateQueries(), })) } const useUpdateInvoiceMutation = (invoiceId: number) => { return useMutation(() => ({ mutationKey: ['invoices', 'update', invoiceId], mutationFn: patchInvoice, onSuccess: () => queryClient.invalidateQueries(), gcTime: 1000 * 10, })) } function RouterSpinner() { const isLoading = useRouterState({ select: (s) => s.status === 'pending' }) return } // Routes // Build our routes. We could do this in our component, too. const rootRoute = createRootRouteWithContext<{ auth: Auth queryClient: QueryClient }>()({ component: RootComponent, }) ``` -------------------------------- ### Implement Scroll Restoration in Solid Source: https://tanstack.com/router/latest/docs/framework/solid/examples/scroll-restoration Demonstrates basic route setup with scroll-aware links and manual scroll restoration for virtualized elements using useElementScrollRestoration. ```tsx import { render } from 'solid-js/web' import { Link, Outlet, RouterProvider, createRootRoute, createRoute, createRouter, useElementScrollRestoration, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import { createVirtualizer } from '@tanstack/solid-virtual' import './styles.css' const rootRoute = createRootRoute({ component: RootComponent, }) function RootComponent() { return ( <>
Home {' '} About About (No Reset) By-Element
) } const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', loader: () => new Promise((r) => setTimeout(r, 500)), component: IndexComponent, }) function IndexComponent() { return (

Welcome Home!

{Array.from({ length: 50 }).map((_, i) => (
Home Item {i + 1}
))}
) } const aboutRoute = createRoute({ getParentRoute: () => rootRoute, path: '/about', loader: () => new Promise((r) => setTimeout(r, 500)), component: AboutComponent, }) function AboutComponent() { return (
Hello from About!
{Array.from({ length: 50 }).map((_, i) => (
About Item {i + 1}
))}
) } const byElementRoute = createRoute({ getParentRoute: () => rootRoute, path: '/by-element', loader: () => new Promise((r) => setTimeout(r, 500)), component: ByElementComponent, }) function ByElementComponent() { // We need a unique ID for manual scroll restoration on a specific element // It should be as unique as possible for this element across your app const scrollRestorationId = 'myVirtualizedContent' // We use that ID to get the scroll entry for this element const scrollEntry = useElementScrollRestoration({ id: scrollRestorationId, }) // Let's use TanStack Virtual to virtualize some content! let virtualizerParentRef: any const virtualizer = createVirtualizer({ count: 10000, getScrollElement: () => virtualizerParentRef, estimateSize: () => 100, // We pass the scrollY from the scroll restoration entry to the virtualizer // as the initial offset initialOffset: scrollEntry?.scrollY, }) ``` -------------------------------- ### Configure Route Definitions Source: https://tanstack.com/router/latest/docs/framework/solid/examples/basic-solid-query Setup for nested pathless routes and the route tree structure. ```typescript const nestedPathlessLayoutRoute = createRoute({ getParentRoute: () => pathlessLayoutRoute, id: '_nestedPathlessLayout', component: NestedPathlessLayoutComponent, }) ``` ```typescript const pathlessLayoutARoute = createRoute({ getParentRoute: () => nestedPathlessLayoutRoute, path: '/route-a', component: PathlessLayoutAComponent, }) ``` ```typescript const pathlessLayoutBRoute = createRoute({ getParentRoute: () => nestedPathlessLayoutRoute, path: '/route-b', component: PathlessLayoutBComponent, }) ``` ```typescript const routeTree = rootRoute.addChildren([ postsLayoutRoute.addChildren([postRoute, postsIndexRoute]), pathlessLayoutRoute.addChildren([ nestedPathlessLayoutRoute.addChildren([ pathlessLayoutARoute, pathlessLayoutBRoute, ]), ]), indexRoute, ]) ``` -------------------------------- ### Home Route Component Source: https://tanstack.com/router/latest/docs/framework/solid/examples/authenticated-routes Displays the entry point for the authenticated routes example, providing navigation options to public and protected pages. ```typescript import { Link, createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/')({ component: HomeComponent, }) function HomeComponent() { return ( # Welcome! **IMPORTANT!!!** This is just an example of how to use authenticated routes with TanStack Router. This is NOT an example how you'd write a production-level authentication system. You'll need to take the concepts and patterns used in this example and adapt then to work with your authentication flow/system for your app. You are currently on the index route of the{' '} **authenticated-routes** example. You can try going through these options. 1. Go to the public login page. 2. Go to the auth-only dashboard page. 3. Go to the auth-only invoices page. ) } ``` -------------------------------- ### Initialize router and application Source: https://tanstack.com/router/latest/docs/framework/solid/examples/deferred-data Configures the router instance and renders the application to the DOM. ```typescript const routeTree = rootRoute.addChildren([ postsRoute.addChildren([postRoute]), indexRoute, ]) // Set up a Router instance const router = createRouter({ routeTree, defaultPreload: 'intent', scrollRestoration: true, }) // Register things for typesafety declare module '@tanstack/solid-router' { interface Register { router: typeof router } } const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render(() => , rootElement) } ``` -------------------------------- ### Initialize Application Source: https://tanstack.com/router/latest/docs/framework/solid/examples/kitchen-sink Entry point script to render the application into the DOM. ```typescript const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render(() => , rootElement) } ``` -------------------------------- ### Initialize Router and Provider in Solid Source: https://tanstack.com/router/latest/docs/framework/solid/examples/basic-file-based Configures the router instance with default preload and stale time settings, and renders the application using the RouterProvider. ```typescript import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import './styles.css' // Set up a Router instance const router = createRouter({ routeTree, defaultPreload: 'intent', defaultStaleTime: 5000, scrollRestoration: true, }) // Register things for typesafety declare module '@tanstack/solid-router' { interface Register { router: typeof router } } const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render(() => , rootElement) } ``` -------------------------------- ### Implement Location Masking with TanStack Router Source: https://tanstack.com/router/latest/docs/framework/solid/examples/location-masking This setup includes route definitions, data fetching, and modal components for handling masked locations. ```typescript import type { JSX } from 'solid-js' import { render } from 'solid-js/web' import { ErrorComponent, Link, Outlet, RouterProvider, createRootRoute, createRoute, createRouteMask, createRouter, useNavigate, useRouterState, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import type { ErrorComponentProps } from '@tanstack/solid-router' import './styles.css' type PhotoType = { id: string title: string url: string thumbnailUrl: string albumId: string } class NotFoundError extends Error {} const fetchPhotos = async () => { console.info('Fetching photos...') await new Promise((r) => setTimeout(r, 500)) // Generate mock photos using picsum.photos since via.placeholder.com is down return Array.from({ length: 10 }, (_, i) => ({ id: String(i + 1), title: `Photo ${i + 1}`, url: `https://picsum.photos/600/400?random=${i + 1}`, thumbnailUrl: `https://picsum.photos/200/200?random=${i + 1}`, albumId: '1', })) } const fetchPhoto = async (photoId: string) => { console.info(`Fetching photo with id ${photoId}...`) await new Promise((r) => setTimeout(r, 500)) // Simulate photo not found for invalid IDs const photoIdNum = parseInt(photoId, 10) if (isNaN(photoIdNum) || photoIdNum < 1 || photoIdNum > 10) { throw new NotFoundError(`Photo with id "${photoId}" not found!`) } // Generate mock photo using picsum.photos return { id: photoId, title: `Photo ${photoId}`, url: `https://picsum.photos/600/400?random=${photoId}`, thumbnailUrl: `https://picsum.photos/200/200?random=${photoId}`, albumId: '1', } } type PhotoModal = { id: 'photo' photoId: string } type ModalObject = PhotoModal export function Spinner() { return (
⍥
) } const rootRoute = createRootRoute({ validateSearch: (search) => search as { modal?: ModalObject }, component: RootComponent, }) function RootComponent() { const status = useRouterState({ select: (s) => s.status }) return ( <>
Home {' '} Photos {' '} {status() === 'pending' ? : null}

{/* Start rendering router matches */} ) } function Modal(props: { children: JSX.Element onOpenChange?: (open: boolean) => void }) { const handleOverlayClick = () => { props.onOpenChange?.(false) } const handleContentClick = (e: MouseEvent) => { e.stopPropagation() } return (
{props.children}
) } const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: () => { return (

Welcome Home!

) }, }) const photosLayoutRoute = createRoute({ getParentRoute: () => rootRoute, path: 'photos', loader: fetchPhotos, component: PhotosRoute, }) function PhotosRoute() { const photos = photosLayoutRoute.useLoaderData() ``` -------------------------------- ### Configure Router and Render Application Source: https://tanstack.com/router/latest/docs/framework/solid/examples/navigation-blocking Initializes the router with the route tree and renders the application to the DOM. ```tsx const routeTree = rootRoute.addChildren([ indexRoute, fooRoute, editor1Route.addChildren([editor2Route]), ]) // Set up a Router instance const router = createRouter({ routeTree, defaultPreload: 'intent', scrollRestoration: true, }) const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render(() => , rootElement) } ``` -------------------------------- ### Configure Router and Route Tree Source: https://tanstack.com/router/latest/docs/framework/solid/examples/kitchen-sink-solid-query Assembles the route tree and initializes the router with QueryClient and global defaults. ```typescript const routeTree = rootRoute.addChildren([ indexRoute, dashboardLayoutRoute.addChildren([ dashboardIndexRoute, invoicesLayoutRoute.addChildren([invoicesIndexRoute, invoiceRoute]), usersLayoutRoute.addChildren([usersIndexRoute, userRoute]), ]), expensiveRoute, authPathlessLayoutRoute.addChildren([profileRoute]), loginRoute, pathlessLayoutRoute.addChildren([pathlessLayoutARoute, pathlessLayoutBRoute]), ]) const queryClient = new QueryClient() const router = createRouter({ routeTree, defaultPendingComponent: () => (
), defaultErrorComponent: ({ error }) => , context: { auth: undefined!, // We'll inject this when we render queryClient, }, defaultPreload: 'intent', // Since we're using React Query, we don't want loader calls to ever be stale // This will ensure that the loader is always called when the route is preloaded or visited defaultPreloadStaleTime: 0, scrollRestoration: true, }) declare module '@tanstack/solid-router' { interface Register { router: typeof router } } ``` -------------------------------- ### Initialize Router and Routes in Solid Source: https://tanstack.com/router/latest/docs/framework/solid/examples/quickstart Defines a root route with navigation links and child routes, then registers the router instance for type safety and rendering. ```typescript import { render } from 'solid-js/web' import { Link, Outlet, RouterProvider, createRootRoute, createRoute, createRouter, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import './styles.css' const rootRoute = createRootRoute({ component: () => ( <>
Home {' '} About

), }) const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: function Index() { return (

Welcome Home!

) }, }) const aboutRoute = createRoute({ getParentRoute: () => rootRoute, path: '/about', component: function About() { return
Hello from About!
}, }) const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) const router = createRouter({ routeTree, defaultPreload: 'intent', scrollRestoration: true, }) declare module '@tanstack/solid-router' { interface Register { router: typeof router } } const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render(() => , rootElement) } ``` -------------------------------- ### Configure Router and QueryClient Source: https://tanstack.com/router/latest/docs/framework/solid/examples/kitchen-sink-solid-query-file-based Initializes the QueryClient and the TanStack Router with custom pending components, context, and preload settings. ```typescript import { render } from 'solid-js/web' import { ErrorComponent, RouterProvider, createRouter, } from '@tanstack/solid-router' import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { auth } from './utils/auth' import { Spinner } from './components/Spinner' import { routeTree } from './routeTree.gen' import { useSessionStorage } from './hooks/useSessionStorage' import './styles.css' // export const queryClient = new QueryClient() const router = createRouter({ routeTree, defaultPendingComponent: () => (
true} />
), defaultErrorComponent: ({ error }) => , context: { auth: undefined!, // We'll inject this when we render queryClient: queryClient, // Type assertion to fix the type mismatch }, defaultPreload: 'intent', // Since we're using Solid Query, we don't want loader calls to ever be stale // This will ensure that the loader is always called when the route is preloaded or visited defaultPreloadStaleTime: 0, scrollRestoration: true, }) declare module '@tanstack/solid-router' { interface Register { router: typeof router } } function App() { // This stuff is just to tweak our sandbox setup in real-time const [loaderDelay, setLoaderDelay] = useSessionStorage('loaderDelay', 500) const [pendingMs, setPendingMs] = useSessionStorage('pendingMs', 1000) const [pendingMinMs, setPendingMinMs] = useSessionStorage('pendingMinMs', 500) return ( <>
Loader Delay: {loaderDelay()}ms
setLoaderDelay(e.target.valueAsNumber)} class="w-full" />
defaultPendingMs: {pendingMs()}ms
setPendingMs(e.target.valueAsNumber)} class="w-full" />
defaultPendingMinMs: {pendingMinMs()}ms
setPendingMinMs(e.target.valueAsNumber)} class="w-full" />
) } const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render( () => ( ), rootElement, ) } ``` -------------------------------- ### Configure Router and QueryClient in main.tsx Source: https://tanstack.com/router/latest/docs/framework/solid/examples/router-monorepo-solid-query Initializes the application by mapping route IDs to components and wrapping the router in a QueryClientProvider. ```typescript import { render } from 'solid-js/web' import { RouterProvider } from '@tanstack/solid-router' import { QueryClientProvider } from '@tanstack/solid-query' import { queryClient, router } from '@router-solid-mono-solid-query/router' import { PostErrorComponent, PostIdComponent, PostsListComponent, } from '@router-solid-mono-solid-query/post-feature' import { RootComponent } from './rootComponent' import type { RouterIds } from '@router-solid-mono-solid-query/router' import './style.css' import type { JSX } from 'solid-js' // Not lazy loaded for simplicity, but you could expose from your library component // individually, and enforce here to use react lazy components via typings // so that you have code splitting const routerMap = { '/': PostsListComponent, '/$postId': PostIdComponent, __root__: RootComponent, } as const satisfies Record JSX.Element> Object.entries(routerMap).forEach(([path, component]) => { const foundRoute = router.routesById[path as RouterIds] foundRoute.update({ component: component, }) }) // And you can do the same logic with custom error pages, and any other properties const errorComponentMap = { '/': null, '/$postId': PostErrorComponent, __root__: null, } Object.entries(errorComponentMap).forEach(([path, component]) => { if (!component) { return } const foundRoute = router.routesById[path as RouterIds] foundRoute.update({ errorComponent: component, }) }) const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render( () => ( ), rootElement, ) } ``` -------------------------------- ### Configure Router with QueryClient Source: https://tanstack.com/router/latest/docs/framework/solid/examples/basic-solid-query-file-based Initializes the QueryClient and integrates it into the router context for use across the application. ```typescript import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { routeTree } from './routeTree.gen' import './styles.css' export const queryClient = new QueryClient() // Set up a Router instance const router = createRouter({ routeTree, context: { queryClient, }, scrollRestoration: true, defaultPreload: 'intent', // Since we're using React Query, we don't want loader calls to ever be stale // This will ensure that the loader is always called when the route is preloaded or visited defaultPreloadStaleTime: 0, }) // Register things for typesafety declare module '@tanstack/solid-router' { interface Register { router: typeof router } } const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render( () => ( ), rootElement, ) } ``` -------------------------------- ### Initialize Router with Auth Context Source: https://tanstack.com/router/latest/docs/framework/solid/examples/authenticated-routes Sets up the router instance with an auth context placeholder and wraps the application in an AuthProvider to inject authentication state. ```typescript import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import { AuthProvider, useAuth } from './auth' import './styles.css' // Set up a Router instance const router = createRouter({ routeTree, defaultPreload: 'intent', scrollRestoration: true, context: { auth: undefined!, // This will be set after we wrap the app in an AuthProvider }, }) // Register things for typesafety declare module '@tanstack/solid-router' { interface Register { router: typeof router } } function InnerApp() { const auth = useAuth() return } function App() { return ( ) } const rootElement = document.getElementById('app')! render(() => , rootElement) ``` -------------------------------- ### Configure Router with View Transitions Source: https://tanstack.com/router/latest/docs/framework/solid/examples/view-transitions Initialize the router with view transition settings. Use defaultViewTransition to enable transitions globally or define a types function for dynamic transition logic. ```typescript import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import './styles.css' // Set up a Router instance const router = createRouter({ routeTree, defaultPreload: 'intent', defaultStaleTime: 5000, scrollRestoration: true, /* Using defaultViewTransition would prevent the need to manually add `viewTransition: true` to every navigation. If defaultViewTransition.types is a function, it will be called with the location change info and should return an array of view transition types. This is useful if you want to have different view transitions depending on the navigation's specifics. An example use case is sliding in a direction based on the index of the previous and next routes when navigating via browser history back and forth. */ // defaultViewTransition: true // OR // defaultViewTransition: { // types: ({ fromLocation, toLocation }) => { // let direction = 'none' // if (fromLocation) { // const fromIndex = fromLocation.state.__TSR_index // const toIndex = toLocation.state.__TSR_index // direction = fromIndex > toIndex ? 'right' : 'left' // } // return [`slide-${direction}`] // }, // }, }) // Register things for typesafety declare module '@tanstack/solid-router' { interface Register { router: typeof router } } const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render(() => , rootElement) } ``` -------------------------------- ### Configure Router and Route Tree Source: https://tanstack.com/router/latest/docs/framework/solid/examples/kitchen-sink Assembles the route tree and initializes the router with global defaults and context. ```typescript const routeTree = rootRoute.addChildren([ indexRoute, dashboardLayoutRoute.addChildren([ dashboardIndexRoute, invoicesLayoutRoute.addChildren([invoicesIndexRoute, invoiceRoute]), usersLayoutRoute.addChildren([usersIndexRoute, userRoute]), ]), expensiveRoute, authPathlessLayoutRoute.addChildren([profileRoute]), loginRoute, pathlessLayoutRoute.addChildren([pathlessLayoutARoute, pathlessLayoutBRoute]), ]) const router = createRouter({ routeTree, defaultPendingComponent: () => (
), defaultErrorComponent: ({ error }) => , context: { auth: undefined!, // We'll inject this when we render }, defaultPreload: 'intent', scrollRestoration: true, }) declare module '@tanstack/solid-router' { interface Register { router: typeof router } } ``` -------------------------------- ### Render Application with Providers Source: https://tanstack.com/router/latest/docs/framework/solid/examples/basic-solid-query Mount the application using QueryClientProvider and RouterProvider. ```typescript const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render( () => ( ), rootElement, ) } ``` -------------------------------- ### Application Initialization Source: https://tanstack.com/router/latest/docs/framework/solid/examples/kitchen-sink-solid-query Renders the application to the DOM if the root element is empty. ```typescript const rootElement = document.getElementById('app')! if (!rootElement.innerHTML) { render(() => , rootElement) } ``` -------------------------------- ### Initialize Router with Auth Context Source: https://tanstack.com/router/latest/docs/framework/solid/examples/authenticated-routes Configures the router instance with an authentication context placeholder to be populated by an AuthProvider. ```typescript import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import { AuthProvider, useAuth } from './auth' import './styles.css' // Set up a Router instance const router = createRouter({ routeTree, defaultPreload: 'intent', scrollRestoration: true, context: { auth: undefined!, // This will be set after we wrap the app in an AuthProvider }, }) // Register things for typesafety declare module '@tanstack/solid-router' { interface Register { ``` -------------------------------- ### Configure Solid Query with TanStack Router Source: https://tanstack.com/router/latest/docs/framework/solid/examples/basic-solid-query Sets up the root route with a queryClient context and defines routes that utilize loaders for data fetching. ```typescript import { ErrorComponent, HeadContent, Link, Outlet, RouterProvider, createRootRouteWithContext, createRoute, createRouter, useRouter, } from '@tanstack/solid-router' import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/solid-query' import './styles.css' import { render } from 'solid-js/web' import { SolidQueryDevtools } from '@tanstack/solid-query-devtools' import { createEffect, createMemo } from 'solid-js' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import { NotFoundError, postQueryOptions, postsQueryOptions } from './posts' import type { ErrorComponentProps } from '@tanstack/solid-router' const rootRoute = createRootRouteWithContext<{ queryClient: QueryClient }>()({ component: RootComponent, notFoundComponent: () => { return (

This is the notFoundComponent configured on root route

Start Over
) }, }) function RootComponent() { return ( <>
Home {' '} Posts {' '} Pathless Layout {' '} This Route Does Not Exist

) } const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: IndexRouteComponent, }) function IndexRouteComponent() { return (

Welcome Home!

) } const postsLayoutRoute = createRoute({ getParentRoute: () => rootRoute, path: 'posts', loader: ({ context: { queryClient } }) => queryClient.ensureQueryData(postsQueryOptions), }).lazy(() => import('./posts.lazy').then((d) => d.Route)) const postsIndexRoute = createRoute({ getParentRoute: () => postsLayoutRoute, path: '/', component: PostsIndexRouteComponent, }) function PostsIndexRouteComponent() { return
Select a post.
} const postRoute = createRoute({ getParentRoute: () => postsLayoutRoute, path: '$postId', errorComponent: PostErrorComponent, loader: ({ context: { queryClient }, params: { postId } }) => queryClient.ensureQueryData(postQueryOptions(postId)), component: PostRouteComponent, }) function PostErrorComponent({ error, reset }: ErrorComponentProps) { const router = useRouter() if (error instanceof NotFoundError) { return
{error.message}
} createEffect(() => { reset() queryClient.resetQueries() }) return (
) } function PostRouteComponent() { const params = postRoute.useParams() const postQuery = useQuery(() => postQueryOptions(params().postId)) const post = createMemo(() => postQuery.data) return (

{post()?.title}

{post()?.body}
) } const pathlessLayoutRoute = createRoute({ getParentRoute: () => rootRoute, id: '_pathlessLayout', component: PathlessLayoutComponent, }) ``` -------------------------------- ### Configure and Render TanStack Router in Solid Source: https://tanstack.com/router/latest/docs/framework/solid/examples/kitchen-sink-file-based Initializes the router with a generated route tree and provides a custom App component that manages global state for testing loading behaviors. ```typescript import * as Solid from 'solid-js' import { ErrorComponent, RouterProvider, createRouter, } from '@tanstack/solid-router' import { auth } from './utils/auth' import { Spinner } from './components/Spinner' import { routeTree } from './routeTree.gen' import { useSessionStorage } from './hooks/useSessionStorage' import './styles.css' import { render } from 'solid-js/web' // const router = createRouter({ routeTree, defaultPendingComponent: () => (
), defaultErrorComponent: ({ error }) => , context: { auth: undefined!, // We'll inject this when we render }, defaultPreload: 'intent', scrollRestoration: true, }) declare module '@tanstack/solid-router' { interface Register { router: typeof router } } function App() { // This stuff is just to tweak our sandbox setup in real-time const [loaderDelay, setLoaderDelay] = useSessionStorage( 'loaderDelay', 500, ) const [pendingMs, setPendingMs] = useSessionStorage('pendingMs', 1000) const [pendingMinMs, setPendingMinMs] = useSessionStorage( 'pendingMinMs', 500, ) return ( <>
Loader Delay: {loaderDelay()}ms
setLoaderDelay(e.target.valueAsNumber)} class="w-full" />
defaultPendingMs: {pendingMs()}ms
setPendingMs(e.target.valueAsNumber)} class="w-full" />
defaultPendingMinMs: {pendingMinMs()}ms
setPendingMinMs(e.target.valueAsNumber)} class="w-full" />
) } const rootElement = document.getElementById('app')! render(() => , rootElement!) ``` -------------------------------- ### Configure Root Route and Navigation Source: https://tanstack.com/router/latest/docs/framework/solid/examples/kitchen-sink Defines the root route with context and implements a layout component with navigation links and a global loading spinner. ```typescript /* eslint-disable @typescript-eslint/no-unnecessary-condition */ import { render } from 'solid-js/web' import { ErrorComponent, Link, MatchRoute, Outlet, RouterProvider, createRootRouteWithContext, createRoute, createRouter, lazyRouteComponent, redirect, retainSearchParams, useNavigate, useRouter, useRouterState, useSearch, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import { createEffect, createMemo, createRenderEffect, createSignal, on, } from 'solid-js' import { z } from 'zod' import { fetchInvoiceById, fetchInvoices, fetchUserById, fetchUsers, patchInvoice, postInvoice, } from './mockTodos' import { useMutation } from './useMutation' import type { Invoice } from './mockTodos' import './styles.css' // type UsersViewSortBy = 'name' | 'id' | 'email' const rootRoute = createRootRouteWithContext<{ auth: Auth }>()({ component: RootComponent, }) function RouterSpinner() { const isLoading = useRouterState({ select: (s) => s.status === 'pending' }) return } function RootComponent() { return ( <>

Kitchen Sink

{/* Show a global spinner when the router is transitioning */}
{( [ ['/', 'Home'], ['/dashboard', 'Dashboard'], ['/expensive', 'Expensive'], ['/route-a', 'Pathless Layout A'], ['/route-b', 'Pathless Layout B'], ['/profile', 'Profile'], ...(auth.status === 'loggedOut' ? [['/login', 'Login']] : []), ] as const ).map(([to, label]) => { return (
{label}
) })}
{/* Render our first route match */}
) } const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: IndexComponent, }) ```