<html lang="en">
<head></head>
<body>

<form id="mainForm" method="post" action="https://stackblitz.com/run" target="_self">
<input type="hidden" name="project[files][.gitignore]" value="node_modules
.DS_Store
dist
dist-ssr
*.local
">
<input type="hidden" name="project[files][README.md]" value="# TanStack Router - Default Search Params Example

An example demonstrating default search parameters.

- [TanStack Router Docs](https://tanstack.com/router)

## Start a new project based on this example

To start a new project based on this example, run:

```sh
npx gitpick TanStack/router/tree/main/examples/react/basic-default-search-params basic-default-search-params
```

## Getting Started

Install dependencies:

```sh
pnpm install
```

Start the development server:

```sh
pnpm dev
```

## Build

Build for production:

```sh
pnpm build
```

## About This Example

This example demonstrates:

- Default search parameter values
- Type-safe search params
- Search param validation
- URL state management
">
<input type="hidden" name="project[files][index.html]" value="&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot; /&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
    &lt;title&gt;Vite App&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;
    &lt;script type=&quot;module&quot; src=&quot;/src/main.tsx&quot;&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
">
<input type="hidden" name="project[files][package.json]" value="{&quot;name&quot;:&quot;tanstack-router-react-example-basic-default-search-params&quot;,&quot;private&quot;:true,&quot;type&quot;:&quot;module&quot;,&quot;scripts&quot;:{&quot;dev&quot;:&quot;vite --port=3000&quot;,&quot;build&quot;:&quot;vite build &amp;&amp; tsc --noEmit&quot;,&quot;preview&quot;:&quot;vite preview&quot;,&quot;start&quot;:&quot;vite&quot;},&quot;dependencies&quot;:{&quot;@tailwindcss/vite&quot;:&quot;^4.1.18&quot;,&quot;@tanstack/react-query&quot;:&quot;^5.90.0&quot;,&quot;@tanstack/react-router&quot;:&quot;https://pkg.pr.new/TanStack/router/@tanstack/react-router@d7ab9056820e6849f34d639f3039559e1427038c&quot;,&quot;@tanstack/react-router-devtools&quot;:&quot;https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@d7ab9056820e6849f34d639f3039559e1427038c&quot;,&quot;react&quot;:&quot;^19.0.0&quot;,&quot;react-dom&quot;:&quot;^19.0.0&quot;,&quot;redaxios&quot;:&quot;^0.5.1&quot;,&quot;tailwindcss&quot;:&quot;^4.1.18&quot;,&quot;zod&quot;:&quot;^3.24.2&quot;},&quot;devDependencies&quot;:{&quot;@types/react&quot;:&quot;^19.0.8&quot;,&quot;@types/react-dom&quot;:&quot;^19.0.3&quot;,&quot;@vitejs/plugin-react&quot;:&quot;^4.3.4&quot;,&quot;typescript&quot;:&quot;^5.7.2&quot;,&quot;vite&quot;:&quot;^7.3.1&quot;}}">
<input type="hidden" name="project[files][tsconfig.json]" value="{
  &quot;compilerOptions&quot;: {
    &quot;strict&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;jsx&quot;: &quot;react-jsx&quot;,
    &quot;target&quot;: &quot;ESNext&quot;,
    &quot;moduleResolution&quot;: &quot;Bundler&quot;,
    &quot;lib&quot;: [&quot;DOM&quot;, &quot;DOM.Iterable&quot;, &quot;ES2022&quot;],
    &quot;skipLibCheck&quot;: true
  }
}
">
<input type="hidden" name="project[files][vite.config.js]" value="import { defineConfig } from &#39;vite&#39;
import react from &#39;@vitejs/plugin-react&#39;
import tailwindcss from &#39;@tailwindcss/vite&#39;

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [tailwindcss(), react()],
})
">
<input type="hidden" name="project[files][.vscode/settings.json]" value="{
  &quot;files.watcherExclude&quot;: {
    &quot;**/routeTree.gen.ts&quot;: true
  },
  &quot;search.exclude&quot;: {
    &quot;**/routeTree.gen.ts&quot;: true
  },
  &quot;files.readonlyInclude&quot;: {
    &quot;**/routeTree.gen.ts&quot;: true
  }
}
">
<input type="hidden" name="project[files][src/main.tsx]" value="import React from &#39;react&#39;
import ReactDOM from &#39;react-dom/client&#39;
import {
  ErrorComponent,
  Link,
  Outlet,
  RouterProvider,
  createRootRoute,
  createRoute,
  createRouter,
} from &#39;@tanstack/react-router&#39;
import { TanStackRouterDevtools } from &#39;@tanstack/react-router-devtools&#39;
import axios from &#39;redaxios&#39;
import { z } from &#39;zod&#39;
import type {
  ErrorComponentProps,
  SearchSchemaInput,
} from &#39;@tanstack/react-router&#39;
import &#39;./styles.css&#39;

type PostType = {
  id: number
  title: string
  body: string
}

const fetchPosts = async () =&gt; {
  console.info(&#39;Fetching posts...&#39;)
  await new Promise((r) =&gt; setTimeout(r, 300))
  return axios
    .get&lt;Array&lt;PostType&gt;&gt;(&#39;https://jsonplaceholder.typicode.com/posts&#39;)
    .then((r) =&gt; r.data.slice(0, 10))
}

const fetchPost = async (postId: number) =&gt; {
  console.info(`Fetching post with id ${postId}...`)
  await new Promise((r) =&gt; setTimeout(r, 300))
  const post = await axios
    .get&lt;PostType&gt;(`https://jsonplaceholder.typicode.com/posts/${postId}`)
    .catch((err) =&gt; {
      if (err.status === 404) {
        throw new NotFoundError(`Post with id &quot;${postId}&quot; not found!`)
      }
      throw err
    })
    .then((r) =&gt; r.data)

  return post
}

const rootRoute = createRootRoute({
  component: RootComponent,
  notFoundComponent: () =&gt; {
    return &lt;p&gt;This is the notFoundComponent configured on root route&lt;/p&gt;
  },
})

function RootComponent() {
  return (
    &lt;div className=&quot;bg-linear-to-r from-green-700 to-lime-600 text-white&quot;&gt;
      &lt;div className=&quot;p-2 flex gap-2 text-lg bg-black/40 shadow-xl&quot;&gt;
        &lt;Link
          to=&quot;/&quot;
          activeProps={{
            className: &#39;font-bold&#39;,
          }}
          activeOptions={{ exact: true }}
        &gt;
          Home
        &lt;/Link&gt;{&#39; &#39;}
        &lt;Link
          to=&quot;/posts&quot;
          activeProps={{
            className: &#39;font-bold&#39;,
          }}
        &gt;
          Posts
        &lt;/Link&gt;{&#39; &#39;}
        &lt;Link
          // @ts-expect-error
          to=&quot;/this-route-does-not-exist&quot;
          activeProps={{
            className: &#39;font-bold&#39;,
          }}
        &gt;
          This Route Does Not Exist
        &lt;/Link&gt;
      &lt;/div&gt;
      &lt;Outlet /&gt;
      &lt;TanStackRouterDevtools position=&quot;bottom-right&quot; /&gt;
    &lt;/div&gt;
  )
}
const indexRoute = createRoute({
  getParentRoute: () =&gt; rootRoute,
  path: &#39;/&#39;,
  component: IndexComponent,
})

function IndexComponent() {
  return (
    &lt;div className=&quot;p-2&quot;&gt;
      &lt;h3&gt;Welcome Home!&lt;/h3&gt;
    &lt;/div&gt;
  )
}

const postsLayoutRoute = createRoute({
  getParentRoute: () =&gt; rootRoute,
  path: &#39;posts&#39;,
  loader: () =&gt; fetchPosts(),
  component: PostsLayoutComponent,
})

function PostsLayoutComponent() {
  const posts = postsLayoutRoute.useLoaderData()

  return (
    &lt;div className=&quot;p-2 flex gap-2&quot;&gt;
      &lt;div className=&quot;list-disc bg-gray-800/70 rounded-lg divide-y divide-green-500/30&quot;&gt;
        {posts.map((post, index) =&gt; {
          return (
            &lt;div key={post.id} className=&quot;whitespace-nowrap&quot;&gt;
              &lt;Link
                to={postRoute.to}
                search={{
                  postId: post.id,
                  color: index % 2 ? &#39;red&#39; : undefined,
                }}
                className=&quot;block py-1 px-2 text-green-300 hover:text-green-200&quot;
                activeProps={{ className: &#39;text-white! font-bold&#39; }}
              &gt;
                &lt;div&gt;{post.title.substring(0, 20)}&lt;/div&gt;
              &lt;/Link&gt;
            &lt;/div&gt;
          )
        })}
      &lt;/div&gt;
      &lt;Outlet /&gt;
    &lt;/div&gt;
  )
}

const postsIndexRoute = createRoute({
  getParentRoute: () =&gt; postsLayoutRoute,
  path: &#39;/&#39;,
  component: PostsIndexComponent,
})

function PostsIndexComponent() {
  return &lt;div&gt;Select a post.&lt;/div&gt;
}

class NotFoundError extends Error {}

const postRoute = createRoute({
  getParentRoute: () =&gt; postsLayoutRoute,
  path: &#39;post&#39;,
  validateSearch: (
    input: {
      postId: number
      color?: &#39;white&#39; | &#39;red&#39; | &#39;green&#39;
    } &amp; SearchSchemaInput,
  ) =&gt;
    z
      .object({
        postId: z.number().catch(1),
        color: z.enum([&#39;white&#39;, &#39;red&#39;, &#39;green&#39;]).catch(&#39;white&#39;),
      })
      .parse(input),
  loaderDeps: ({ search: { postId } }) =&gt; ({
    postId,
  }),
  errorComponent: PostErrorComponent,
  loader: ({ deps: { postId } }) =&gt; fetchPost(postId),
  component: PostComponent,
})

function PostErrorComponent({ error }: ErrorComponentProps) {
  if (error instanceof NotFoundError) {
    return &lt;div&gt;{error.message}&lt;/div&gt;
  }

  return &lt;ErrorComponent error={error} /&gt;
}

function PostComponent() {
  const post = postRoute.useLoaderData()
  const { color } = postRoute.useSearch()
  return (
    &lt;div className=&quot;space-y-2&quot;&gt;
      &lt;h4 className=&quot;text-xl font-bold&quot;&gt;{post.title}&lt;/h4&gt;
      &lt;hr className=&quot;opacity-20&quot; /&gt;
      &lt;div className={`text-sm  text-${color}-300`}&gt;{post.body}&lt;/div&gt;
    &lt;/div&gt;
  )
}

const routeTree = rootRoute.addChildren([
  postsLayoutRoute.addChildren([postRoute, postsIndexRoute]),
  indexRoute,
])

// Set up a Router instance
const router = createRouter({
  routeTree,
  defaultPreload: &#39;intent&#39;,
  defaultStaleTime: 5000,
  scrollRestoration: true,
})

// Register things for typesafety
declare module &#39;@tanstack/react-router&#39; {
  interface Register {
    router: typeof router
  }
}

const rootElement = document.getElementById(&#39;app&#39;)!

if (!rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement)

  root.render(&lt;RouterProvider router={router} /&gt;)
}
">
<input type="hidden" name="project[files][src/styles.css]" value="@import &#39;tailwindcss&#39; source(&#39;../&#39;);

@layer base {
  *,
  ::after,
  ::before,
  ::backdrop,
  ::file-selector-button {
    border-color: var(--color-gray-200, currentcolor);
  }
}
">
<input type="hidden" name="project[description]" value="generated by https://pkg.pr.new">
<input type="hidden" name="project[template]" value="node">
<input type="hidden" name="project[title]" value="tanstack-router-react-example-basic-default-search-params">
</form>
<script>document.getElementById("mainForm").submit();</script>

</body></html>