Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

main.tsx

338 lines7.8 KB

1import React from 'react'
2import ReactDOM from 'react-dom/client'
3import {
4 ErrorComponent,
5 Link,
6 Outlet,
7 RouterProvider,
8 createRootRoute,
9 createRoute,
10 createRouteMask,
11 createRouter,
12 useNavigate,
13 useRouterState,
14} from '@tanstack/react-router'
15import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
16import axios from 'redaxios'
17import * as Dialog from '@radix-ui/react-dialog'
18import type { ErrorComponentProps } from '@tanstack/react-router'
19import './styles.css'
20​
21type PhotoType = {
22 id: string
23 title: string
24 url: string
25 thumbnailUrl: string
26 albumId: string
28​
29class NotFoundError extends Error {}
30​
31const fetchPhotos = async () => {
32 console.info('Fetching photos...')
33 await new Promise((r) => setTimeout(r, 500))
34 return axios
35 .get<Array<PhotoType>>('https://jsonplaceholder.typicode.com/photos')
36 .then((r) => r.data.slice(0, 10))
38​
39const fetchPhoto = async (photoId: string) => {
40 console.info(`Fetching photo with id ${photoId}...`)
41 await new Promise((r) => setTimeout(r, 500))
42 const photo = await axios
43 .get<PhotoType>(`https://jsonplaceholder.typicode.com/photos/${photoId}`)
44 .then((r) => r.data)
45 .catch((err) => {
46 if (err.status === 404) {
47 throw new NotFoundError(`Photo with id "${photoId}" not found!`)
48 }
49 throw err
50 })
51​
52 return photo
54​
55type PhotoModal = {
56 id: 'photo'
57 photoId: string
59​
60type ModalObject = PhotoModal
61​
62export function Spinner() {
63 return (
64 <div className="animate-spin px-3 text-xl inline-flex items-center justify-center">
65 β₯
66 </div>
67 )
69​
70const rootRoute = createRootRoute({
71 validateSearch: (search) =>
72 search as {
73 modal?: ModalObject
74 },
75 component: RootComponent,
76})
77​
78function RootComponent() {
79 const status = useRouterState({ select: (s) => s.status })
80​
81 return (
82 <>
83 <div className="p-2 flex gap-2 text-lg">
84 <Link
85 to="/"
86 activeProps={{
87 className: 'font-bold',
88 }}
89 activeOptions={{ exact: true }}
90 >
91 Home
92 </Link>{' '}
93 <Link
94 to="/photos"
95 activeProps={{
96 className: 'font-bold',
97 }}
98 >
99 Photos
100 </Link>{' '}
101 {status === 'pending' ? <Spinner /> : null}
102 </div>
103 <hr />
104 <Outlet />
105 {/* Start rendering router matches */}
106 <TanStackRouterDevtools position="bottom-right" />
107 </>
108 )
110​
111function Modal(props: Dialog.DialogProps) {
112 return (
113 <Dialog.Root open {...props}>
114 <Dialog.Portal>
115 <Dialog.Overlay className="fixed inset-0 bg-black/70" />
116 <Dialog.DialogContent className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
117 {props.children}
118 </Dialog.DialogContent>
119 </Dialog.Portal>
120 </Dialog.Root>
121 )
123​
124const indexRoute = createRoute({
125 getParentRoute: () => rootRoute,
126 path: '/',
127 component: () => {
128 return (
129 <div className="p-2">
130 <h3>Welcome Home!</h3>
131 </div>
132 )
133 },
134})
135const photosLayoutRoute = createRoute({
136 getParentRoute: () => rootRoute,
137 path: 'photos',
138 loader: fetchPhotos,
139 component: PhotosRoute,
140})
141​
142function PhotosRoute() {
143 const photos = photosLayoutRoute.useLoaderData()
144​
145 return (
146 <div className="p-2 space-y-2">
147 <ul className="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-2">
148 {[
149 ...photos,
150 { id: 'i-do-not-exist', title: 'Missing Photo Test', url: '' },
151 ].map((photo) => {
152 return (
153 <li key={photo.id} className="">
154 <Link
155 to={photoModalRoute.to}
156 params={{
157 photoId: photo.id,
158 }}
159 // If you want to use a mask, you can do so like this, but
160 // it's generally safer to set up a route mask instead.
161 // mask={{
162 // to: photoRoute.to,
163 // params: {
164 // photoId: photo.id,
165 // },
166 // }}
167 className="whitespace-nowrap border rounded-lg shadow-xs flex items-center hover:shadow-lg text-blue-600 hover:scale-[1.1] overflow-hidden transition-all"
168 >
169 <img src={photo.url} alt={photo.title} className="max-w-full" />
170 </Link>
171 </li>
172 )
173 })}
174 </ul>
175 <Outlet />
176 </div>
177 )
179​
180const photoRoute = createRoute({
181 getParentRoute: () => rootRoute,
182 path: 'photos/$photoId',
183 loader: async ({ params: { photoId } }) => fetchPhoto(photoId),
184 errorComponent: PhotoErrorComponent,
185 component: PhotoComponent,
186})
187​
188function PhotoErrorComponent({ error }: ErrorComponentProps) {
189 return (
190 <div className="p-4">
191 {(() => {
192 if (error instanceof NotFoundError) {
193 return <div>{error.message}</div>
194 }
195 return <ErrorComponent error={error} />
196 })()}
197 </div>
198 )
200​
201function PhotoComponent() {
202 const photo = photoRoute.useLoaderData()
203​
204 return (
205 <div className="p-4">
206 <Photo photo={photo} />
207 </div>
208 )
210​
211const photoModalRoute = createRoute({
212 getParentRoute: () => photosLayoutRoute,
213 path: '$photoId/modal',
214 loader: async ({ params: { photoId } }) => fetchPhoto(photoId),
215 errorComponent: PhotoModalErrorComponent,
216 // pendingComponent: PhotoModalPendingComponent,
217 component: PhotoModalComponent,
218})
219​
220function PhotoModalErrorComponent({ error }: ErrorComponentProps) {
221 const navigate = useNavigate()
222​
223 return (
224 <Modal
225 onOpenChange={(open) => {
226 if (!open) {
227 navigate({
228 to: photosLayoutRoute.to,
229 })
230 }
231 }}
232 >
233 <div className="bg-gray-100 dark:bg-gray-800 p-2 rounded-lg">
234 {(() => {
235 if (error instanceof NotFoundError) {
236 return <div>{error.message}</div>
237 }
238 return <ErrorComponent error={error} />
239 })()}
240 </div>
241 </Modal>
242 )
244​
245function PhotoModalPendingComponent() {
246 const navigate = useNavigate()
247​
248 return (
249 <Modal
250 onOpenChange={(open) => {
251 if (!open) {
252 navigate({
253 to: photosLayoutRoute.to,
254 })
255 }
256 }}
257 >
258 <div className="bg-gray-100 dark:bg-gray-800 p-2 rounded-lg">
259 <Spinner />
260 </div>
261 </Modal>
262 )
264​
265function PhotoModalComponent() {
266 const navigate = useNavigate()
267 const photo = photoModalRoute.useLoaderData()
268​
269 return (
270 <Modal
271 onOpenChange={(open) => {
272 if (!open) {
273 navigate({
274 to: photosLayoutRoute.to,
275 })
276 }
277 }}
278 >
279 <div className="bg-gray-100 dark:bg-gray-800 p-2 rounded-lg">
280 <Link
281 to="."
282 target="_blank"
283 className="text-blue-600 hover:opacity-75 underline"
284 >
285 Open in new tab (to test de-masking)
286 </Link>
287 <Photo photo={photo} />
288 </div>
289 </Modal>
290 )
292​
293function Photo({ photo }: { photo: PhotoType }) {
294 return (
295 <div className="space-y-2">
296 <h4 className="text-xl font-bold underline">{photo.title}</h4>
297 <div className="">
298 <img src={photo.url} alt={photo.title} className="max-w-full" />
299 </div>
300 </div>
301 )
303​
304const routeTree = rootRoute.addChildren([
305 photoRoute,
306 photosLayoutRoute.addChildren([photoModalRoute]),
307 indexRoute,
308])
309​
310const photoModalToPhotoMask = createRouteMask({
311 routeTree,
312 from: '/photos/$photoId/modal',
313 to: '/photos/$photoId',
314 params: true,
315})
316​
317// Set up a Router instance
318const router = createRouter({
319 routeTree,
320 routeMasks: [photoModalToPhotoMask],
321 defaultPreload: 'intent',
322 scrollRestoration: true,
323})
324​
325// Register things for typesafety
326declare module '@tanstack/react-router' {
327 interface Register {
328 router: typeof router
329 }
331​
332const rootElement = document.getElementById('app')!
333​
334if (!rootElement.innerHTML) {
335 const root = ReactDOM.createRoot(rootElement)
336​
337 root.render(<RouterProvider router={router} />)