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

index.tsx

155 lines2.9 KB

1/* eslint-disable @typescript-eslint/no-use-before-define */
2import React from "react";
3import ReactDOM from "react-dom";
4import {
5 Link,
6 MakeGenerics,
7 Outlet,
8 ReactLocation,
9 Router,
10 useMatch,
11} from "@tanstack/react-location";
12import axios from "axios";
13​
14type PostType = {
15 id: string;
16 title: string;
17 body: string;
18};
19​
20type LocationGenerics = MakeGenerics<{
21 LoaderData: {
22 posts: PostType[];
23 post: PostType;
24 };
25}>;
26​
27// Set up a ReactLocation instance
28const location = new ReactLocation();
29​
30function App() {
31 return (
32 // Build our routes and render our router
33 <Router
34 location={location}
35 routes={[
36 { path: "/", element: <Index /> },
37 {
38 path: "posts",
39 element: <Posts />,
40 loader: async () => {
41 return {
42 posts: await fetchPosts(),
43 };
44 },
45 children: [
46 { path: "/", element: <PostsIndex /> },
47 {
48 path: ":postId",
49 element: <Post />,
50 loader: async ({ params: { postId } }) => {
51 return {
52 post: await fetchPostById(postId),
53 };
54 },
55 },
56 ],
57 },
58 ]}
59 >
60 <div>
61 <Link
62 to="/"
63 getActiveProps={getActiveProps}
64 activeOptions={{ exact: true }}
65 >
66 Home
67 </Link>{" "}
68 <Link to="posts" getActiveProps={getActiveProps}>
69 Posts
70 </Link>
71 </div>
72 <hr />
73 <Outlet /> {/* Start rendering router matches */}
74 </Router>
75 );
77​
78async function fetchPosts() {
79 await new Promise((r) => setTimeout(r, 300));
80 return await axios
81 .get("https://jsonplaceholder.typicode.com/posts")
82 .then((r) => r.data.slice(0, 5));
84​
85async function fetchPostById(postId: string) {
86 await new Promise((r) => setTimeout(r, 300));
87​
88 return await axios
89 .get(`https://jsonplaceholder.typicode.com/posts/${postId}`)
90 .then((r) => r.data);
92​
93function Index() {
94 return (
95 <div>
96 <h3>Welcome Home!</h3>
97 </div>
98 );
100​
101function Posts() {
102 const {
103 data: { posts },
104 } = useMatch<LocationGenerics>();
105​
106 return (
107 <div>
108 <div>
109 {posts?.map((post) => {
110 return (
111 <div key={post.id}>
112 <Link to={post.id} getActiveProps={getActiveProps}>
113 <pre>{post.title}</pre>
114 </Link>
115 </div>
116 );
117 })}
118 </div>
119 <hr />
120 <Outlet />
121 </div>
122 );
124​
125function PostsIndex() {
126 return (
127 <>
128 <div>Select an post.</div>
129 </>
130 );
132​
133function Post() {
134 const {
135 data: { post },
136 } = useMatch<LocationGenerics>();
137​
138 return (
139 <div>
140 <h4>{post?.title}</h4>
141 <p>{post?.body}</p>
142 </div>
143 );
145​
146function getActiveProps() {
147 return {
148 style: {
149 fontWeight: "bold",
150 },
151 };
153​
154const rootElement = document.getElementById("root");
155ReactDOM.render(<App />, rootElement);