Open History to see the last commit
1import * as React from 'react'
2import * as ReactDOM from 'react-dom/client'
3import { AnimatePresence, motion } from 'framer-motion'
4import {
5 ErrorComponent,
6 Link,
7 Outlet,
8 RouterProvider,
9 createRootRoute,
10 createRoute,
11 createRouter,
12 useMatch,
13 useMatches,
14} from '@tanstack/react-router'
15import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
16import axios from 'redaxios'
17import './styles.css'
18β
19type PostType = {
20 id: string
21 title: string
22 body: string
23}
24β
25const fetchPosts = async () => {
26 console.info('Fetching posts...')
27 await new Promise((r) => setTimeout(r, 500))
28 return axios
29 .get<Array<PostType>>('https://jsonplaceholder.typicode.com/posts')
30 .then((r) => r.data.slice(0, 10))
31}
32β
33const fetchPost = async (postId: string) => {
34 console.info(`Fetching post with id ${postId}...`)
35 await new Promise((r) => setTimeout(r, 500))
36 const post = await axios
37 .get<PostType>(`https://jsonplaceholder.typicode.com/posts/${postId}`)
38 .then((r) => r.data)
39β
40 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
41 if (!post) {
42 throw new NotFoundError(`Post with id "${postId}" not found!`)
43 }
44β
45 return post
46}
47β
48export const mainTransitionProps = {
49 initial: { y: -20, opacity: 0, position: 'absolute' },
50 animate: { y: 0, opacity: 1, damping: 5 },
51 exit: { y: 60, opacity: 0 },
52 transition: {
53 type: 'spring',
54 stiffness: 150,
55 damping: 10,
56 },
57} as const
58β
59export const postTransitionProps = {
60 initial: { y: -20, opacity: 0 },
61 animate: { y: 0, opacity: 1, damping: 5 },
62 exit: { y: 60, opacity: 0 },
63 transition: {
64 type: 'spring',
65 stiffness: 150,
66 damping: 10,
67 },
68} as const
69β
70const rootRoute = createRootRoute({
71 component: () => {
72 const matches = useMatches()
73 const match = useMatch({ strict: false })
74 const nextMatchIndex = matches.findIndex((d) => d.id === match.id) + 1
75 const nextMatch = matches[nextMatchIndex]
76β
77 return (
78 <>
79 <div className="p-2 flex gap-2 text-lg">
80 <Link
81 to="/"
82 activeProps={{
83 className: 'font-bold',
84 }}
85 activeOptions={{ exact: true }}
86 >
87 Home
88 </Link>{' '}
89 <Link
90 to="/posts"
91 activeProps={{
92 className: 'font-bold',
93 }}
94 >
95 Posts
96 </Link>
97 </div>
98 <hr />
99 <AnimatePresence mode="wait">
100 <Outlet key={nextMatch.id} />
101 </AnimatePresence>
102 {/* Start rendering router matches */}
103 <TanStackRouterDevtools position="bottom-right" />
104 </>
105 )
106 },
107})
108β
109const indexRoute = createRoute({
110 getParentRoute: () => rootRoute,
111 path: '/',
112 component: () => {
113 return (
114 <motion.div className="p-2" {...mainTransitionProps}>
115 <h3>Welcome Home!</h3>
116 </motion.div>
117 )
118 },
119})
120β
121const postsLayoutRoute = createRoute({
122 getParentRoute: () => rootRoute,
123 path: 'posts',
124 loader: () => fetchPosts(),
125 component: () => {
126 const posts = postsLayoutRoute.useLoaderData()
127 return (
128 <motion.div className="p-2 flex gap-2" {...mainTransitionProps}>
129 <ul className="list-disc pl-4">
130 {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map(
131 (post) => {
132 return (
133 <li key={post.id} className="whitespace-nowrap">
134 <Link
135 to={postRoute.to}
136 params={{
137 postId: post.id,
138 }}
139 className="block py-1 text-blue-800 hover:text-blue-600"
140 activeProps={{ className: 'text-black font-bold' }}
141 >
142 <div>{post.title.substring(0, 20)}</div>
143 </Link>
144 </li>
145 )
146 },
147 )}
148 </ul>
149 <hr />
150 <AnimatePresence>
151 <Outlet />
152 </AnimatePresence>
153 </motion.div>
154 )
155 },
156})
157β
158const postsIndexRoute = createRoute({
159 getParentRoute: () => postsLayoutRoute,
160 path: '/',
161 component: () => <div>Select a post.</div>,
162})
163β
164class NotFoundError extends Error {}
165β
166const postRoute = createRoute({
167 getParentRoute: () => postsLayoutRoute,
168 path: '$postId',
169 loader: ({ params: { postId } }) => fetchPost(postId),
170 errorComponent: ErrorComponent,
171 component: () => {
172 const post = postRoute.useLoaderData()
173 return (
174 <motion.div className="space-y-2" {...postTransitionProps}>
175 <h4 className="text-xl font-bold underline">{post.title}</h4>
176 <div className="text-sm">{post.body}</div>
177 </motion.div>
178 )
179 },
180})
181β
182const routeTree = rootRoute.addChildren([
183 postsLayoutRoute.addChildren([postRoute, postsIndexRoute]),
184 indexRoute,
185])
186β
187// Set up a Router instance
188const router = createRouter({
189 routeTree,
190 defaultPreload: 'intent',
191 scrollRestoration: true,
192 context: {
193 // loaderClient,
194 },
195})
196β
197// Register things for typesafety
198declare module '@tanstack/react-router' {
199 interface Register {
200 router: typeof router
201 }
202}
203β
204const rootElement = document.getElementById('app')!
205β
206if (!rootElement.innerHTML) {
207 const root = ReactDOM.createRoot(rootElement)
208β
209 root.render(
210 <React.StrictMode>
211 <RouterProvider router={router} />
212 </React.StrictMode>,
213 )
214}