Open History to see the last commit
1import React from 'react'
2import ReactDOM from 'react-dom/client'
3import {
4 ErrorComponent,
5 Link,
6 Outlet,
7 RouterProvider,
8 createRootRoute,
9 createRoute,
10 createRouter,
11} from '@tanstack/react-router'
12import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
13import axios from 'redaxios'
14import { z } from 'zod'
15import type {
16 ErrorComponentProps,
17 SearchSchemaInput,
18} from '@tanstack/react-router'
19import './styles.css'
20β
21type PostType = {
22 id: number
23 title: string
24 body: string
25}
26β
27const fetchPosts = async () => {
28 console.info('Fetching posts...')
29 await new Promise((r) => setTimeout(r, 300))
30 return axios
31 .get<Array<PostType>>('https://jsonplaceholder.typicode.com/posts')
32 .then((r) => r.data.slice(0, 10))
33}
34β
35const fetchPost = async (postId: number) => {
36 console.info(`Fetching post with id ${postId}...`)
37 await new Promise((r) => setTimeout(r, 300))
38 const post = await axios
39 .get<PostType>(`https://jsonplaceholder.typicode.com/posts/${postId}`)
40 .catch((err) => {
41 if (err.status === 404) {
42 throw new NotFoundError(`Post with id "${postId}" not found!`)
43 }
44 throw err
45 })
46 .then((r) => r.data)
47β
48 return post
49}
50β
51const rootRoute = createRootRoute({
52 component: RootComponent,
53 notFoundComponent: () => {
54 return <p>This is the notFoundComponent configured on root route</p>
55 },
56})
57β
58function RootComponent() {
59 return (
60 <div className="bg-linear-to-r from-green-700 to-lime-600 text-white">
61 <div className="p-2 flex gap-2 text-lg bg-black/40 shadow-xl">
62 <Link
63 to="/"
64 activeProps={{
65 className: 'font-bold',
66 }}
67 activeOptions={{ exact: true }}
68 >
69 Home
70 </Link>{' '}
71 <Link
72 to="/posts"
73 activeProps={{
74 className: 'font-bold',
75 }}
76 >
77 Posts
78 </Link>{' '}
79 <Link
80 // @ts-expect-error
81 to="/this-route-does-not-exist"
82 activeProps={{
83 className: 'font-bold',
84 }}
85 >
86 This Route Does Not Exist
87 </Link>
88 </div>
89 <Outlet />
90 <TanStackRouterDevtools position="bottom-right" />
91 </div>
92 )
93}
94const indexRoute = createRoute({
95 getParentRoute: () => rootRoute,
96 path: '/',
97 component: IndexComponent,
98})
99β
100function IndexComponent() {
101 return (
102 <div className="p-2">
103 <h3>Welcome Home!</h3>
104 </div>
105 )
106}
107β
108const postsLayoutRoute = createRoute({
109 getParentRoute: () => rootRoute,
110 path: 'posts',
111 loader: () => fetchPosts(),
112 component: PostsLayoutComponent,
113})
114β
115function PostsLayoutComponent() {
116 const posts = postsLayoutRoute.useLoaderData()
117β
118 return (
119 <div className="p-2 flex gap-2">
120 <div className="list-disc bg-gray-800/70 rounded-lg divide-y divide-green-500/30">
121 {posts.map((post, index) => {
122 return (
123 <div key={post.id} className="whitespace-nowrap">
124 <Link
125 to={postRoute.to}
126 search={{
127 postId: post.id,
128 color: index % 2 ? 'red' : undefined,
129 }}
130 className="block py-1 px-2 text-green-300 hover:text-green-200"
131 activeProps={{ className: 'text-white! font-bold' }}
132 >
133 <div>{post.title.substring(0, 20)}</div>
134 </Link>
135 </div>
136 )
137 })}
138 </div>
139 <Outlet />
140 </div>
141 )
142}
143β
144const postsIndexRoute = createRoute({
145 getParentRoute: () => postsLayoutRoute,
146 path: '/',
147 component: PostsIndexComponent,
148})
149β
150function PostsIndexComponent() {
151 return <div>Select a post.</div>
152}
153β
154class NotFoundError extends Error {}
155β
156const postRoute = createRoute({
157 getParentRoute: () => postsLayoutRoute,
158 path: 'post',
159 validateSearch: (
160 input: {
161 postId: number
162 color?: 'white' | 'red' | 'green'
163 } & SearchSchemaInput,
164 ) =>
165 z
166 .object({
167 postId: z.number().catch(1),
168 color: z.enum(['white', 'red', 'green']).catch('white'),
169 })
170 .parse(input),
171 loaderDeps: ({ search: { postId } }) => ({
172 postId,
173 }),
174 errorComponent: PostErrorComponent,
175 loader: ({ deps: { postId } }) => fetchPost(postId),
176 component: PostComponent,
177})
178β
179function PostErrorComponent({ error }: ErrorComponentProps) {
180 if (error instanceof NotFoundError) {
181 return <div>{error.message}</div>
182 }
183β
184 return <ErrorComponent error={error} />
185}
186β
187function PostComponent() {
188 const post = postRoute.useLoaderData()
189 const { color } = postRoute.useSearch()
190 return (
191 <div className="space-y-2">
192 <h4 className="text-xl font-bold">{post.title}</h4>
193 <hr className="opacity-20" />
194 <div className={`text-sm text-${color}-300`}>{post.body}</div>
195 </div>
196 )
197}
198β
199const routeTree = rootRoute.addChildren([
200 postsLayoutRoute.addChildren([postRoute, postsIndexRoute]),
201 indexRoute,
202])
203β
204// Set up a Router instance
205const router = createRouter({
206 routeTree,
207 defaultPreload: 'intent',
208 defaultStaleTime: 5000,
209 scrollRestoration: true,
210})
211β
212// Register things for typesafety
213declare module '@tanstack/react-router' {
214 interface Register {
215 router: typeof router
216 }
217}
218β
219const rootElement = document.getElementById('app')!
220β
221if (!rootElement.innerHTML) {
222 const root = ReactDOM.createRoot(rootElement)
223β
224 root.render(<RouterProvider router={router} />)
225}