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 createRootRouteWithContext,
9 createRoute,
10 createRouter,
11 useRouter,
12} from '@tanstack/react-router'
13import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
14import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
15import {
16 QueryClient,
17 QueryClientProvider,
18 useQueryErrorResetBoundary,
19 useSuspenseQuery,
20} from '@tanstack/react-query'
21import { NotFoundError, postQueryOptions, postsQueryOptions } from './posts'
22import type { ErrorComponentProps } from '@tanstack/react-router'
23import './styles.css'
24β
25const rootRoute = createRootRouteWithContext<{
26 queryClient: QueryClient
27}>()({
28 component: RootComponent,
29 notFoundComponent: () => {
30 return (
31 <div>
32 <p>This is the notFoundComponent configured on root route</p>
33 <Link to="/">Start Over</Link>
34 </div>
35 )
36 },
37})
38β
39function RootComponent() {
40 return (
41 <>
42 <div className="p-2 flex gap-2 text-lg">
43 <Link
44 to="/"
45 activeProps={{
46 className: 'font-bold',
47 }}
48 activeOptions={{ exact: true }}
49 >
50 Home
51 </Link>{' '}
52 <Link
53 to="/posts"
54 activeProps={{
55 className: 'font-bold',
56 }}
57 >
58 Posts
59 </Link>{' '}
60 <Link
61 to="/route-a"
62 activeProps={{
63 className: 'font-bold',
64 }}
65 >
66 Pathless Layout
67 </Link>{' '}
68 <Link
69 // @ts-expect-error
70 to="/this-route-does-not-exist"
71 activeProps={{
72 className: 'font-bold',
73 }}
74 >
75 This Route Does Not Exist
76 </Link>
77 </div>
78 <hr />
79 <Outlet />
80 <ReactQueryDevtools buttonPosition="top-right" />
81 <TanStackRouterDevtools position="bottom-right" />
82 </>
83 )
84}
85β
86const indexRoute = createRoute({
87 getParentRoute: () => rootRoute,
88 path: '/',
89 component: IndexRouteComponent,
90})
91β
92function IndexRouteComponent() {
93 return (
94 <div className="p-2">
95 <h3>Welcome Home!</h3>
96 </div>
97 )
98}
99β
100const postsLayoutRoute = createRoute({
101 getParentRoute: () => rootRoute,
102 path: 'posts',
103 loader: ({ context: { queryClient } }) =>
104 queryClient.ensureQueryData(postsQueryOptions),
105}).lazy(() => import('./posts.lazy').then((d) => d.Route))
106β
107const postsIndexRoute = createRoute({
108 getParentRoute: () => postsLayoutRoute,
109 path: '/',
110 component: PostsIndexRouteComponent,
111})
112β
113function PostsIndexRouteComponent() {
114 return <div>Select a post.</div>
115}
116β
117const postRoute = createRoute({
118 getParentRoute: () => postsLayoutRoute,
119 path: '$postId',
120 errorComponent: PostErrorComponent,
121 loader: ({ context: { queryClient }, params: { postId } }) =>
122 queryClient.ensureQueryData(postQueryOptions(postId)),
123 component: PostRouteComponent,
124})
125β
126function PostErrorComponent({ error }: ErrorComponentProps) {
127 const router = useRouter()
128 if (error instanceof NotFoundError) {
129 return <div>{error.message}</div>
130 }
131 const queryErrorResetBoundary = useQueryErrorResetBoundary()
132β
133 React.useEffect(() => {
134 queryErrorResetBoundary.reset()
135 }, [queryErrorResetBoundary])
136β
137 return (
138 <div>
139 <button
140 onClick={() => {
141 router.invalidate()
142 }}
143 >
144 retry
145 </button>
146 <ErrorComponent error={error} />
147 </div>
148 )
149}
150β
151function PostRouteComponent() {
152 const { postId } = postRoute.useParams()
153 const postQuery = useSuspenseQuery(postQueryOptions(postId))
154 const post = postQuery.data
155β
156 return (
157 <div className="space-y-2">
158 <h4 className="text-xl font-bold underline">{post.title}</h4>
159 <div className="text-sm">{post.body}</div>
160 </div>
161 )
162}
163β
164const pathlessLayoutRoute = createRoute({
165 getParentRoute: () => rootRoute,
166 id: '_pathlessLayout',
167 component: PathlessLayoutComponent,
168})
169β
170function PathlessLayoutComponent() {
171 return (
172 <div className="p-2">
173 <div className="border-b">I'm a pathless layout</div>
174 <div>
175 <Outlet />
176 </div>
177 </div>
178 )
179}
180β
181const nestedPathlessLayoutRoute = createRoute({
182 getParentRoute: () => pathlessLayoutRoute,
183 id: '_nestedPathlessLayout',
184 component: Layout2Component,
185})
186β
187function Layout2Component() {
188 return (
189 <div>
190 <div>I'm a nested pathless layout</div>
191 <div className="flex gap-2 border-b">
192 <Link
193 to="/route-a"
194 activeProps={{
195 className: 'font-bold',
196 }}
197 >
198 Go to route A
199 </Link>
200 <Link
201 to="/route-b"
202 activeProps={{
203 className: 'font-bold',
204 }}
205 >
206 Go to route B
207 </Link>
208 </div>
209 <div>
210 <Outlet />
211 </div>
212 </div>
213 )
214}
215β
216const pathlessLayoutARoute = createRoute({
217 getParentRoute: () => nestedPathlessLayoutRoute,
218 path: '/route-a',
219 component: PathlessLayoutAComponent,
220})
221β
222function PathlessLayoutAComponent() {
223 return <div>I'm layout A!</div>
224}
225β
226const pathlessLayoutBRoute = createRoute({
227 getParentRoute: () => nestedPathlessLayoutRoute,
228 path: '/route-b',
229 component: PathlessLayoutBComponent,
230})
231β
232function PathlessLayoutBComponent() {
233 return <div>I'm layout B!</div>
234}
235β
236const routeTree = rootRoute.addChildren([
237 postsLayoutRoute.addChildren([postRoute, postsIndexRoute]),
238 pathlessLayoutRoute.addChildren([
239 nestedPathlessLayoutRoute.addChildren([
240 pathlessLayoutARoute,
241 pathlessLayoutBRoute,
242 ]),
243 ]),
244 indexRoute,
245])
246β
247const queryClient = new QueryClient()
248β
249// Set up a Router instance
250const router = createRouter({
251 routeTree,
252 defaultPreload: 'intent',
253 // Since we're using React Query, we don't want loader calls to ever be stale
254 // This will ensure that the loader is always called when the route is preloaded or visited
255 defaultPreloadStaleTime: 0,
256 scrollRestoration: true,
257 context: {
258 queryClient,
259 },
260})
261β
262// Register things for typesafety
263declare module '@tanstack/react-router' {
264 interface Register {
265 router: typeof router
266 }
267}
268β
269const rootElement = document.getElementById('app')!
270β
271if (!rootElement.innerHTML) {
272 const root = ReactDOM.createRoot(rootElement)
273β
274 root.render(
275 <QueryClientProvider client={queryClient}>
276 <RouterProvider router={router} />
277 </QueryClientProvider>,
278 )
279}