)
}
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 (
<>
)
},
})
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: () => (
<>
},
})
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 (
<>
>
)
}
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