@tanstack/react-router 1.121.16 → 1.121.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/package.json +2 -2
  2. package/dist/cjs/Asset.cjs +0 -41
  3. package/dist/cjs/Asset.cjs.map +0 -1
  4. package/dist/cjs/Asset.d.cts +0 -2
  5. package/dist/cjs/CatchBoundary.cjs +0 -114
  6. package/dist/cjs/CatchBoundary.cjs.map +0 -1
  7. package/dist/cjs/CatchBoundary.d.cts +0 -12
  8. package/dist/cjs/ClientOnly.cjs +0 -20
  9. package/dist/cjs/ClientOnly.cjs.map +0 -1
  10. package/dist/cjs/ClientOnly.d.cts +0 -29
  11. package/dist/cjs/HeadContent.cjs +0 -155
  12. package/dist/cjs/HeadContent.cjs.map +0 -1
  13. package/dist/cjs/HeadContent.d.cts +0 -7
  14. package/dist/cjs/Match.cjs +0 -257
  15. package/dist/cjs/Match.cjs.map +0 -1
  16. package/dist/cjs/Match.d.cts +0 -8
  17. package/dist/cjs/Matches.cjs +0 -136
  18. package/dist/cjs/Matches.cjs.map +0 -1
  19. package/dist/cjs/Matches.d.cts +0 -26
  20. package/dist/cjs/RouterProvider.cjs +0 -33
  21. package/dist/cjs/RouterProvider.cjs.map +0 -1
  22. package/dist/cjs/RouterProvider.d.cts +0 -10
  23. package/dist/cjs/SafeFragment.cjs +0 -8
  24. package/dist/cjs/SafeFragment.cjs.map +0 -1
  25. package/dist/cjs/SafeFragment.d.cts +0 -1
  26. package/dist/cjs/ScriptOnce.cjs +0 -28
  27. package/dist/cjs/ScriptOnce.cjs.map +0 -1
  28. package/dist/cjs/ScriptOnce.d.cts +0 -5
  29. package/dist/cjs/Scripts.cjs +0 -51
  30. package/dist/cjs/Scripts.cjs.map +0 -1
  31. package/dist/cjs/Scripts.d.cts +0 -1
  32. package/dist/cjs/ScrollRestoration.cjs +0 -39
  33. package/dist/cjs/ScrollRestoration.cjs.map +0 -1
  34. package/dist/cjs/ScrollRestoration.d.cts +0 -14
  35. package/dist/cjs/Transitioner.cjs +0 -115
  36. package/dist/cjs/Transitioner.cjs.map +0 -1
  37. package/dist/cjs/Transitioner.d.cts +0 -1
  38. package/dist/cjs/awaited.cjs +0 -48
  39. package/dist/cjs/awaited.cjs.map +0 -1
  40. package/dist/cjs/awaited.d.cts +0 -10
  41. package/dist/cjs/fileRoute.cjs +0 -107
  42. package/dist/cjs/fileRoute.cjs.map +0 -1
  43. package/dist/cjs/fileRoute.d.cts +0 -54
  44. package/dist/cjs/history.d.cts +0 -8
  45. package/dist/cjs/index.cjs +0 -289
  46. package/dist/cjs/index.cjs.map +0 -1
  47. package/dist/cjs/index.d.cts +0 -55
  48. package/dist/cjs/lazyRouteComponent.cjs +0 -78
  49. package/dist/cjs/lazyRouteComponent.cjs.map +0 -1
  50. package/dist/cjs/lazyRouteComponent.d.cts +0 -2
  51. package/dist/cjs/link.cjs +0 -324
  52. package/dist/cjs/link.cjs.map +0 -1
  53. package/dist/cjs/link.d.cts +0 -48
  54. package/dist/cjs/matchContext.cjs +0 -27
  55. package/dist/cjs/matchContext.cjs.map +0 -1
  56. package/dist/cjs/matchContext.d.cts +0 -3
  57. package/dist/cjs/not-found.cjs +0 -40
  58. package/dist/cjs/not-found.cjs.map +0 -1
  59. package/dist/cjs/not-found.d.cts +0 -9
  60. package/dist/cjs/renderRouteNotFound.cjs +0 -22
  61. package/dist/cjs/renderRouteNotFound.cjs.map +0 -1
  62. package/dist/cjs/renderRouteNotFound.d.cts +0 -2
  63. package/dist/cjs/route.cjs +0 -205
  64. package/dist/cjs/route.cjs.map +0 -1
  65. package/dist/cjs/route.d.cts +0 -95
  66. package/dist/cjs/router.cjs +0 -22
  67. package/dist/cjs/router.cjs.map +0 -1
  68. package/dist/cjs/router.d.cts +0 -72
  69. package/dist/cjs/routerContext.cjs +0 -33
  70. package/dist/cjs/routerContext.cjs.map +0 -1
  71. package/dist/cjs/routerContext.d.cts +0 -8
  72. package/dist/cjs/scroll-restoration.cjs +0 -24
  73. package/dist/cjs/scroll-restoration.cjs.map +0 -1
  74. package/dist/cjs/scroll-restoration.d.cts +0 -1
  75. package/dist/cjs/serializer.d.cts +0 -6
  76. package/dist/cjs/structuralSharing.d.cts +0 -8
  77. package/dist/cjs/typePrimitives.d.cts +0 -16
  78. package/dist/cjs/useBlocker.cjs +0 -165
  79. package/dist/cjs/useBlocker.cjs.map +0 -1
  80. package/dist/cjs/useBlocker.d.cts +0 -66
  81. package/dist/cjs/useCanGoBack.cjs +0 -8
  82. package/dist/cjs/useCanGoBack.cjs.map +0 -1
  83. package/dist/cjs/useCanGoBack.d.cts +0 -1
  84. package/dist/cjs/useLoaderData.cjs +0 -15
  85. package/dist/cjs/useLoaderData.cjs.map +0 -1
  86. package/dist/cjs/useLoaderData.d.cts +0 -8
  87. package/dist/cjs/useLoaderDeps.cjs +0 -14
  88. package/dist/cjs/useLoaderDeps.cjs.map +0 -1
  89. package/dist/cjs/useLoaderDeps.d.cts +0 -8
  90. package/dist/cjs/useLocation.cjs +0 -10
  91. package/dist/cjs/useLocation.cjs.map +0 -1
  92. package/dist/cjs/useLocation.d.cts +0 -7
  93. package/dist/cjs/useMatch.cjs +0 -47
  94. package/dist/cjs/useMatch.cjs.map +0 -1
  95. package/dist/cjs/useMatch.d.cts +0 -10
  96. package/dist/cjs/useNavigate.cjs +0 -55
  97. package/dist/cjs/useNavigate.cjs.map +0 -1
  98. package/dist/cjs/useNavigate.d.cts +0 -5
  99. package/dist/cjs/useParams.cjs +0 -16
  100. package/dist/cjs/useParams.cjs.map +0 -1
  101. package/dist/cjs/useParams.d.cts +0 -9
  102. package/dist/cjs/useRouteContext.cjs +0 -11
  103. package/dist/cjs/useRouteContext.cjs.map +0 -1
  104. package/dist/cjs/useRouteContext.d.cts +0 -3
  105. package/dist/cjs/useRouter.cjs +0 -32
  106. package/dist/cjs/useRouter.cjs.map +0 -1
  107. package/dist/cjs/useRouter.d.cts +0 -4
  108. package/dist/cjs/useRouterState.cjs +0 -29
  109. package/dist/cjs/useRouterState.cjs.map +0 -1
  110. package/dist/cjs/useRouterState.d.cts +0 -8
  111. package/dist/cjs/useSearch.cjs +0 -16
  112. package/dist/cjs/useSearch.cjs.map +0 -1
  113. package/dist/cjs/useSearch.d.cts +0 -9
  114. package/dist/cjs/utils.cjs +0 -72
  115. package/dist/cjs/utils.cjs.map +0 -1
  116. package/dist/cjs/utils.d.cts +0 -49
  117. package/dist/esm/Asset.d.ts +0 -2
  118. package/dist/esm/Asset.js +0 -41
  119. package/dist/esm/Asset.js.map +0 -1
  120. package/dist/esm/CatchBoundary.d.ts +0 -12
  121. package/dist/esm/CatchBoundary.js +0 -97
  122. package/dist/esm/CatchBoundary.js.map +0 -1
  123. package/dist/esm/ClientOnly.d.ts +0 -29
  124. package/dist/esm/ClientOnly.js +0 -20
  125. package/dist/esm/ClientOnly.js.map +0 -1
  126. package/dist/esm/HeadContent.d.ts +0 -7
  127. package/dist/esm/HeadContent.js +0 -139
  128. package/dist/esm/HeadContent.js.map +0 -1
  129. package/dist/esm/Match.d.ts +0 -8
  130. package/dist/esm/Match.js +0 -240
  131. package/dist/esm/Match.js.map +0 -1
  132. package/dist/esm/Matches.d.ts +0 -26
  133. package/dist/esm/Matches.js +0 -119
  134. package/dist/esm/Matches.js.map +0 -1
  135. package/dist/esm/RouterProvider.d.ts +0 -10
  136. package/dist/esm/RouterProvider.js +0 -33
  137. package/dist/esm/RouterProvider.js.map +0 -1
  138. package/dist/esm/SafeFragment.d.ts +0 -1
  139. package/dist/esm/SafeFragment.js +0 -8
  140. package/dist/esm/SafeFragment.js.map +0 -1
  141. package/dist/esm/ScriptOnce.d.ts +0 -5
  142. package/dist/esm/ScriptOnce.js +0 -28
  143. package/dist/esm/ScriptOnce.js.map +0 -1
  144. package/dist/esm/Scripts.d.ts +0 -1
  145. package/dist/esm/Scripts.js +0 -51
  146. package/dist/esm/Scripts.js.map +0 -1
  147. package/dist/esm/ScrollRestoration.d.ts +0 -14
  148. package/dist/esm/ScrollRestoration.js +0 -39
  149. package/dist/esm/ScrollRestoration.js.map +0 -1
  150. package/dist/esm/Transitioner.d.ts +0 -1
  151. package/dist/esm/Transitioner.js +0 -98
  152. package/dist/esm/Transitioner.js.map +0 -1
  153. package/dist/esm/awaited.d.ts +0 -10
  154. package/dist/esm/awaited.js +0 -31
  155. package/dist/esm/awaited.js.map +0 -1
  156. package/dist/esm/fileRoute.d.ts +0 -54
  157. package/dist/esm/fileRoute.js +0 -107
  158. package/dist/esm/fileRoute.js.map +0 -1
  159. package/dist/esm/history.d.ts +0 -8
  160. package/dist/esm/index.d.ts +0 -55
  161. package/dist/esm/index.js +0 -151
  162. package/dist/esm/index.js.map +0 -1
  163. package/dist/esm/lazyRouteComponent.d.ts +0 -2
  164. package/dist/esm/lazyRouteComponent.js +0 -61
  165. package/dist/esm/lazyRouteComponent.js.map +0 -1
  166. package/dist/esm/link.d.ts +0 -48
  167. package/dist/esm/link.js +0 -307
  168. package/dist/esm/link.js.map +0 -1
  169. package/dist/esm/matchContext.d.ts +0 -3
  170. package/dist/esm/matchContext.js +0 -10
  171. package/dist/esm/matchContext.js.map +0 -1
  172. package/dist/esm/not-found.d.ts +0 -9
  173. package/dist/esm/not-found.js +0 -40
  174. package/dist/esm/not-found.js.map +0 -1
  175. package/dist/esm/renderRouteNotFound.d.ts +0 -2
  176. package/dist/esm/renderRouteNotFound.js +0 -22
  177. package/dist/esm/renderRouteNotFound.js.map +0 -1
  178. package/dist/esm/route.d.ts +0 -95
  179. package/dist/esm/route.js +0 -205
  180. package/dist/esm/route.js.map +0 -1
  181. package/dist/esm/router.d.ts +0 -72
  182. package/dist/esm/router.js +0 -22
  183. package/dist/esm/router.js.map +0 -1
  184. package/dist/esm/routerContext.d.ts +0 -8
  185. package/dist/esm/routerContext.js +0 -16
  186. package/dist/esm/routerContext.js.map +0 -1
  187. package/dist/esm/scroll-restoration.d.ts +0 -1
  188. package/dist/esm/scroll-restoration.js +0 -24
  189. package/dist/esm/scroll-restoration.js.map +0 -1
  190. package/dist/esm/serializer.d.ts +0 -6
  191. package/dist/esm/structuralSharing.d.ts +0 -8
  192. package/dist/esm/typePrimitives.d.ts +0 -16
  193. package/dist/esm/useBlocker.d.ts +0 -66
  194. package/dist/esm/useBlocker.js +0 -148
  195. package/dist/esm/useBlocker.js.map +0 -1
  196. package/dist/esm/useCanGoBack.d.ts +0 -1
  197. package/dist/esm/useCanGoBack.js +0 -8
  198. package/dist/esm/useCanGoBack.js.map +0 -1
  199. package/dist/esm/useLoaderData.d.ts +0 -8
  200. package/dist/esm/useLoaderData.js +0 -15
  201. package/dist/esm/useLoaderData.js.map +0 -1
  202. package/dist/esm/useLoaderDeps.d.ts +0 -8
  203. package/dist/esm/useLoaderDeps.js +0 -14
  204. package/dist/esm/useLoaderDeps.js.map +0 -1
  205. package/dist/esm/useLocation.d.ts +0 -7
  206. package/dist/esm/useLocation.js +0 -10
  207. package/dist/esm/useLocation.js.map +0 -1
  208. package/dist/esm/useMatch.d.ts +0 -10
  209. package/dist/esm/useMatch.js +0 -30
  210. package/dist/esm/useMatch.js.map +0 -1
  211. package/dist/esm/useNavigate.d.ts +0 -5
  212. package/dist/esm/useNavigate.js +0 -38
  213. package/dist/esm/useNavigate.js.map +0 -1
  214. package/dist/esm/useParams.d.ts +0 -9
  215. package/dist/esm/useParams.js +0 -16
  216. package/dist/esm/useParams.js.map +0 -1
  217. package/dist/esm/useRouteContext.d.ts +0 -3
  218. package/dist/esm/useRouteContext.js +0 -11
  219. package/dist/esm/useRouteContext.js.map +0 -1
  220. package/dist/esm/useRouter.d.ts +0 -4
  221. package/dist/esm/useRouter.js +0 -15
  222. package/dist/esm/useRouter.js.map +0 -1
  223. package/dist/esm/useRouterState.d.ts +0 -8
  224. package/dist/esm/useRouterState.js +0 -29
  225. package/dist/esm/useRouterState.js.map +0 -1
  226. package/dist/esm/useSearch.d.ts +0 -9
  227. package/dist/esm/useSearch.js +0 -16
  228. package/dist/esm/useSearch.js.map +0 -1
  229. package/dist/esm/utils.d.ts +0 -49
  230. package/dist/esm/utils.js +0 -55
  231. package/dist/esm/utils.js.map +0 -1
  232. package/dist/llms/index.d.ts +0 -3
  233. package/dist/llms/index.js +0 -35
  234. package/dist/llms/rules/api.d.ts +0 -2
  235. package/dist/llms/rules/api.js +0 -4241
  236. package/dist/llms/rules/guide.d.ts +0 -2
  237. package/dist/llms/rules/guide.js +0 -6225
  238. package/dist/llms/rules/routing.d.ts +0 -2
  239. package/dist/llms/rules/routing.js +0 -1946
  240. package/dist/llms/rules/setup-and-architecture.d.ts +0 -2
  241. package/dist/llms/rules/setup-and-architecture.js +0 -932
@@ -1,932 +0,0 @@
1
- export default `# Overview
2
-
3
- **TanStack Router is a router for building React and Solid applications**. Some of its features include:
4
-
5
- - 100% inferred TypeScript support
6
- - Typesafe navigation
7
- - Nested Routing and layout routes (with pathless layouts)
8
- - Built-in Route Loaders w/ SWR Caching
9
- - Designed for client-side data caches (TanStack Query, SWR, etc.)
10
- - Automatic route prefetching
11
- - Asynchronous route elements and error boundaries
12
- - File-based Route Generation
13
- - Typesafe JSON-first Search Params state management APIs
14
- - Path and Search Parameter Schema Validation
15
- - Search Param Navigation APIs
16
- - Custom Search Param parser/serializer support
17
- - Search param middleware
18
- - Route matching/loading middleware
19
-
20
- To get started quickly, head to the next page. For a more lengthy explanation, buckle up while I bring you up to speed!
21
-
22
- ## "A Fork in the Route"
23
-
24
- Using a router to build applications is widely regarded as a must-have and is usually one of the first choices you’ll make in your tech stack.
25
-
26
- [//]: # 'WhyChooseTanStackRouter'
27
-
28
- **So, why should you choose TanStack Router over another router?**
29
-
30
- To answer this question, we need to look at the other options in the space. There are many if you look hard enough, but in my experience, only a couple are worth exploring seriously:
31
-
32
- - **Next.js** - Widely regarded as the de facto framework for starting a new React project, it’s laser focused on performance, workflow, and bleeding edge technology. Its APIs and abstractions are powerful, but can sometimes come across as non-standard. Its extremely fast growth and adoption in the industry has resulted in a featured packed experience, but not at the expense of feeling overwhelming and sometimes bloated.
33
- - **Remix / React Router** - A full-stack framework based on the historically successful React Router offers a similarly powerful developer and user experience, with APIs and vision based firmly on web standards like Request/Response and a focus on running anywhere JS can run. Many of its APIs and abstractions are wonderfully designed and were inspiration for more than a few TanStack Router APIs. That said, its rigid design, bolted-on type safety and sometimes strict over-adherence to platform APIs can leave some developers wanting more.
34
-
35
- Both of these frameworks (and their routers) are great, and I can personally attest that both are very good solutions for building React applications. My experience has also taught me that these solutions could also be much better, especially around the actual routing APIs that are available to developers to make their apps faster, easier, and more enjoyable to work with.
36
-
37
- It's probably no surprise at this point that picking a router is so important that it is often tied 1-to-1 with your choice of framework, since most frameworks rely on a specific router.
38
-
39
- [//]: # 'WhyChooseTanStackRouter'
40
-
41
- **Does this mean that TanStack Router is a framework?**
42
-
43
- TanStack Router itself is not a "framework" in the traditional sense, since it doesn't address a few other common full-stack concerns. However TanStack Router has been designed to be upgradable to a full-stack framework when used in conjunction with other tools that address bundling, deployments, and server-side-specific functionality. This is why we are currently developing [TanStack Start](https://tanstack.com/start), a full-stack framework that is built on top of TanStack Router and Vite.
44
-
45
- For a deeper dive on the history of TanStack Router, feel free to read [TanStack Router's History](../decisions-on-dx.md#tanstack-routers-origin-story).
46
-
47
- ## Why TanStack Router?
48
-
49
- TanStack Router delivers on the same fundamental expectations as other routers that you’ve come to expect:
50
-
51
- - Nested routes, layout routes, grouped routes
52
- - File-based Routing
53
- - Parallel data loading
54
- - Prefetching
55
- - URL Path Params
56
- - Error Boundaries and Handling
57
- - SSR
58
- - Route Masking
59
-
60
- And it also delivers some new features that raise the bar:
61
-
62
- - 100% inferred TypeScript support
63
- - Typesafe navigation
64
- - Built-in SWR Caching for loaders
65
- - Designed for client-side data caches (TanStack Query, SWR, etc.)
66
- - Typesafe JSON-first Search Params state management APIs
67
- - Path and Search Parameter Schema Validation
68
- - Search Parameter Navigation APIs
69
- - Custom Search Param parser/serializer support
70
- - Search param middleware
71
- - Inherited Route Context
72
- - Mixed file-based and code-based routing
73
-
74
- Let’s dive into some of the more important ones in more detail!
75
-
76
- ## 100% Inferred TypeScript Support
77
-
78
- Everything these days is written “in Typescript” or at the very least offers type definitions that are veneered over runtime functionality, but too few packages in the ecosystem actually design their APIs with TypeScript in mind. So while I’m pleased that your router is auto-completing your option fields and catching a few property/method typos here and there, there is much more to be had.
79
-
80
- - TanStack Router is fully aware of all of your routes and their configuration at any given point in your code. This includes the path, path params, search params, context, and any other configuration you’ve provided. Ultimately this means that you can navigate to any route in your app with 100% type safety and confidence that your link or navigate call will succeed.
81
- - TanStack Router provides lossless type-inference. It uses countless generic type parameters to enforce and propagate any type information you give it throughout the rest of its API and ultimately your app. No other router offers this level of type safety and developer confidence.
82
-
83
- What does all of that mean for you?
84
-
85
- - Faster feature development with auto-completion and type hints
86
- - Safer and faster refactors
87
- - Confidence that your code will work as expected
88
-
89
- ## 1st Class Search Parameters
90
-
91
- Search parameters are often an afterthought, treated like a black box of strings (or string) that you can parse and update, but not much else. Existing solutions are **not** type-safe either, adding to the caution that is required to deal with them. Even the most "modern" frameworks and routers and leave it up to you to figure out how to manage this state. Sometimes they'll parse the search string into an object for you, or sometimes you're left to do it yourself with \`URLSearchParams\`.
92
-
93
- Let's step back and remember that **search params are the most powerful state manager in your entire application.** They are global, serializable, bookmarkable, and shareable making them the perfect place to store any kind of state that needs to survive a page refresh or a social share.
94
-
95
- To live up to that responsibility, search parameters are a first-class citizen in TanStack Router. While still based on standard URLSearchParams, TanStack Router uses a powerful parser/serializer to manage deeper and more complex data structures in your search params, all while keeping them type-safe and easy to work with.
96
-
97
- **It's like having \`useState\` right in the URL!**
98
-
99
- Search parameters are:
100
-
101
- - Automatically parsed and serialized as JSON
102
- - Validated and typed
103
- - Inherited from parent routes
104
- - Accessible in loaders, components, and hooks
105
- - Easily modified with the useSearch hook, Link, navigate, and router.navigate APIs
106
- - Customizable with a custom search filters and middleware
107
- - Subscribed via fine-grained search param selectors for efficient re-renders
108
-
109
- Once you start using TanStack Router's search parameters, you'll wonder how you ever lived without them.
110
-
111
- ## Built-In Caching and Friendly Data Loading
112
-
113
- Data loading is a critical part of any application and while most existing routers offer some form of critical data loading APIs, they often fall short when it comes to caching and data lifecycle management. Existing solutions suffer from a few common problems:
114
-
115
- - No caching at all. Data is always fresh, but your users are left waiting for frequently accessed data to load over and over again.
116
- - Overly-aggressive caching. Data is cached for too long, leading to stale data and a poor user experience.
117
- - Blunt invalidation strategies and APIs. Data may be invalidated too often, leading to unnecessary network requests and wasted resources, or you may not have any fine-grained control over when data is invalidated at all.
118
-
119
- TanStack Router solves these problems with a two-prong approach to caching and data loading:
120
-
121
- ### Built-in Cache
122
-
123
- TanStack Router provides a light-weight built-in caching layer that works seamlessly with the Router. This caching layer is loosely based on TanStack Query, but with fewer features and a much smaller API surface area. Like TanStack Query, sane but powerful defaults guarantee that your data is cached for reuse, invalidated when necessary, and garbage collected when not in use. It also provides a simple API for invalidating the cache manually when needed.
124
-
125
- ### Flexible & Powerful Data Lifecycle APIs
126
-
127
- TanStack Router is designed with a flexible and powerful data loading API that more easily integrates with existing data fetching libraries like TanStack Query, SWR, Apollo, Relay, or even your own custom data fetching solution. Configurable APIs like \`context\`, \`beforeLoad\`, \`loaderDeps\` and \`loader\` work in unison to make it easy to define declarative data dependencies, prefetch data, and manage the lifecycle of an external data source with ease.
128
-
129
- ## Inherited Route Context
130
-
131
- TanStack Router's router and route context is a powerful feature that allows you to define context that is specific to a route which is then inherited by all child routes. Even the router and root routes themselves can provide context. Context can be built up both synchronously and asynchronously, and can be used to share data, configuration, or even functions between routes and route configurations. This is especially useful for scenarios like:
132
-
133
- - Authentication and Authorization
134
- - Hybrid SSR/CSR data fetching and preloading
135
- - Theming
136
- - Singletons and global utilities
137
- - Curried or partial application across preloading, loading, and rendering stages
138
-
139
- Also, what would route context be if it weren't type-safe? TanStack Router's route context is fully type-safe and inferred at zero cost to you.
140
-
141
- ## File-based and/or Code-Based Routing
142
-
143
- TanStack Router supports both file-based and code-based routing at the same time. This flexibility allows you to choose the approach that best fits your project's needs.
144
-
145
- TanStack Router's file-based routing approach is uniquely user-facing. Route configuration is generated for you either by the Vite plugin or TanStack Router CLI, leaving the usage of said generated code up to you! This means that you're always in total control of your routes and router, even if you use file-based routing.
146
-
147
- ## Acknowledgements
148
-
149
- TanStack Router builds on concepts and patterns popularized by many other OSS projects, including:
150
-
151
- - [TRPC](https://trpc.io/)
152
- - [Remix](https://remix.run)
153
- - [Chicane](https://swan-io.github.io/chicane/)
154
- - [Next.js](https://nextjs.org)
155
-
156
- We acknowledge the investment, risk and research that went into their development, but are excited to push the bar they have set even higher.
157
-
158
- ## Let's go!
159
-
160
- Enough overview, there's so much more to do with TanStack Router. Hit that next button and let's get started!
161
-
162
- # Quick Start
163
-
164
- If you're feeling impatient and prefer to skip all of our wonderful documentation, here is the bare minimum to get going with TanStack Router using both file-based route generation and code-based route configuration:
165
-
166
- ## Using File-Based Route Generation
167
-
168
- File based route generation (through Vite, and other supported bundlers) is the recommended way to use TanStack Router as it provides the best experience, performance, and ergonomics for the least amount of effort.
169
-
170
- ### Scaffolding Your First TanStack Router Project
171
-
172
- \`\`\`sh
173
- npx create-tsrouter-app@latest my-app --template file-router
174
- \`\`\`
175
-
176
- See [create-tsrouter-app](https://github.com/TanStack/create-tsrouter-app/tree/main/cli/create-tsrouter-app) for more options.
177
-
178
- ### Manual Setup
179
-
180
- Alternatively, you can manually setup the project using the following steps:
181
-
182
- #### Install TanStack Router, Vite Plugin, and the Router Devtools
183
-
184
- \`\`\`sh
185
- npm install @tanstack/react-router @tanstack/react-router-devtools
186
- npm install -D @tanstack/router-plugin
187
- # or
188
- pnpm add @tanstack/react-router @tanstack/react-router-devtools
189
- pnpm add -D @tanstack/router-plugin
190
- # or
191
- yarn add @tanstack/react-router @tanstack/react-router-devtools
192
- yarn add -D @tanstack/router-plugin
193
- # or
194
- bun add @tanstack/react-router @tanstack/react-router-devtools
195
- bun add -D @tanstack/router-plugin
196
- # or
197
- deno add npm:@tanstack/react-router npm:@tanstack/router-plugin npm:@tanstack/react-router-devtools
198
- \`\`\`
199
-
200
- #### Configure the Vite Plugin
201
-
202
- \`\`\`tsx
203
- // vite.config.ts
204
- import { defineConfig } from 'vite'
205
- import react from '@vitejs/plugin-react'
206
- import { tanstackRouter } from '@tanstack/router-plugin/vite'
207
-
208
- // https://vitejs.dev/config/
209
- export default defineConfig({
210
- plugins: [
211
- // Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react'
212
- tanstackRouter({
213
- target: 'react',
214
- autoCodeSplitting: true,
215
- }),
216
- react(),
217
- // ...,
218
- ],
219
- })
220
- \`\`\`
221
-
222
- > [!TIP]
223
- > If you are not using Vite, or any of the supported bundlers, you can check out the [TanStack Router CLI](../routing/installation-with-router-cli.md) guide for more info.
224
-
225
- Create the following files:
226
-
227
- - \`src/routes/__root.tsx\` (with two '\`_\`' characters)
228
- - \`src/routes/index.tsx\`
229
- - \`src/routes/about.tsx\`
230
- - \`src/main.tsx\`
231
-
232
- #### \`src/routes/__root.tsx\`
233
-
234
- \`\`\`tsx
235
- import { createRootRoute, Link, Outlet } from '@tanstack/react-router'
236
- import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
237
-
238
- export const Route = createRootRoute({
239
- component: () => (
240
- <>
241
- <div className="p-2 flex gap-2">
242
- <Link to="/" className="[&.active]:font-bold">
243
- Home
244
- </Link>{' '}
245
- <Link to="/about" className="[&.active]:font-bold">
246
- About
247
- </Link>
248
- </div>
249
- <hr />
250
- <Outlet />
251
- <TanStackRouterDevtools />
252
- </>
253
- ),
254
- })
255
- \`\`\`
256
-
257
- #### \`src/routes/index.tsx\`
258
-
259
- \`\`\`tsx
260
- import { createFileRoute } from '@tanstack/react-router'
261
-
262
- export const Route = createFileRoute('/')({
263
- component: Index,
264
- })
265
-
266
- function Index() {
267
- return (
268
- <div className="p-2">
269
- <h3>Welcome Home!</h3>
270
- </div>
271
- )
272
- }
273
- \`\`\`
274
-
275
- #### \`src/routes/about.tsx\`
276
-
277
- \`\`\`tsx
278
- import { createFileRoute } from '@tanstack/react-router'
279
-
280
- export const Route = createFileRoute('/about')({
281
- component: About,
282
- })
283
-
284
- function About() {
285
- return <div className="p-2">Hello from About!</div>
286
- }
287
- \`\`\`
288
-
289
- #### \`src/main.tsx\`
290
-
291
- Regardless of whether you are using the \`@tanstack/router-plugin\` package and running the \`npm run dev\`/\`npm run build\` scripts, or manually running the \`tsr watch\`/\`tsr generate\` commands from your package scripts, the route tree file will be generated at \`src/routeTree.gen.ts\`.
292
-
293
- Import the generated route tree and create a new router instance:
294
-
295
- \`\`\`tsx
296
- import { StrictMode } from 'react'
297
- import ReactDOM from 'react-dom/client'
298
- import { RouterProvider, createRouter } from '@tanstack/react-router'
299
-
300
- // Import the generated route tree
301
- import { routeTree } from './routeTree.gen'
302
-
303
- // Create a new router instance
304
- const router = createRouter({ routeTree })
305
-
306
- // Register the router instance for type safety
307
- declare module '@tanstack/react-router' {
308
- interface Register {
309
- router: typeof router
310
- }
311
- }
312
-
313
- // Render the app
314
- const rootElement = document.getElementById('root')!
315
- if (!rootElement.innerHTML) {
316
- const root = ReactDOM.createRoot(rootElement)
317
- root.render(
318
- <StrictMode>
319
- <RouterProvider router={router} />
320
- </StrictMode>,
321
- )
322
- }
323
- \`\`\`
324
-
325
- If you are working with this pattern you should change the \`id\` of the root \`<div>\` on your \`index.html\` file to \`<div id='root'></div>\`
326
-
327
- ## Using Code-Based Route Configuration
328
-
329
- > [!IMPORTANT]
330
- > The following example shows how to configure routes using code, and for simplicity's sake is in a single file for this demo. While code-based generation allows you to declare many routes and even the router instance in a single file, we recommend splitting your routes into separate files for better organization and performance as your application grows.
331
-
332
- \`\`\`tsx
333
- import { StrictMode } from 'react'
334
- import ReactDOM from 'react-dom/client'
335
- import {
336
- Outlet,
337
- RouterProvider,
338
- Link,
339
- createRouter,
340
- createRoute,
341
- createRootRoute,
342
- } from '@tanstack/react-router'
343
- import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
344
-
345
- const rootRoute = createRootRoute({
346
- component: () => (
347
- <>
348
- <div className="p-2 flex gap-2">
349
- <Link to="/" className="[&.active]:font-bold">
350
- Home
351
- </Link>{' '}
352
- <Link to="/about" className="[&.active]:font-bold">
353
- About
354
- </Link>
355
- </div>
356
- <hr />
357
- <Outlet />
358
- <TanStackRouterDevtools />
359
- </>
360
- ),
361
- })
362
-
363
- const indexRoute = createRoute({
364
- getParentRoute: () => rootRoute,
365
- path: '/',
366
- component: function Index() {
367
- return (
368
- <div className="p-2">
369
- <h3>Welcome Home!</h3>
370
- </div>
371
- )
372
- },
373
- })
374
-
375
- const aboutRoute = createRoute({
376
- getParentRoute: () => rootRoute,
377
- path: '/about',
378
- component: function About() {
379
- return <div className="p-2">Hello from About!</div>
380
- },
381
- })
382
-
383
- const routeTree = rootRoute.addChildren([indexRoute, aboutRoute])
384
-
385
- const router = createRouter({ routeTree })
386
-
387
- declare module '@tanstack/react-router' {
388
- interface Register {
389
- router: typeof router
390
- }
391
- }
392
-
393
- const rootElement = document.getElementById('app')!
394
- if (!rootElement.innerHTML) {
395
- const root = ReactDOM.createRoot(rootElement)
396
- root.render(
397
- <StrictMode>
398
- <RouterProvider router={router} />
399
- </StrictMode>,
400
- )
401
- }
402
- \`\`\`
403
-
404
- If you glossed over these examples or didn't understand something, we don't blame you, because there's so much more to learn to really take advantage of TanStack Router! Let's move on.
405
-
406
- # Devtools
407
-
408
- > Link, take this sword... I mean Devtools!... to help you on your way!
409
-
410
- Wave your hands in the air and shout hooray because TanStack Router comes with dedicated devtools! 🥳
411
-
412
- When you begin your TanStack Router journey, you'll want these devtools by your side. They help visualize all of the inner workings of TanStack Router and will likely save you hours of debugging if you find yourself in a pinch!
413
-
414
- ## Installation
415
-
416
- The devtools are a separate package that you need to install:
417
-
418
- \`\`\`sh
419
- npm install @tanstack/react-router-devtools
420
- \`\`\`
421
-
422
- or
423
-
424
- \`\`\`sh
425
- pnpm add @tanstack/react-router-devtools
426
- \`\`\`
427
-
428
- or
429
-
430
- \`\`\`sh
431
- yarn add @tanstack/react-router-devtools
432
- \`\`\`
433
-
434
- or
435
-
436
- \`\`\`sh
437
- bun add @tanstack/react-router-devtools
438
- \`\`\`
439
-
440
- ## Import the Devtools
441
-
442
- \`\`\`js
443
- import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
444
- \`\`\`
445
-
446
- ## Using Devtools in production
447
-
448
- The Devtools, if imported as \`TanStackRouterDevtools\` will not be shown in production. If you want to have devtools in an environment with \`process.env.NODE_ENV === 'production'\`, use instead \`TanStackRouterDevtoolsInProd\`, which has all the same options:
449
-
450
- \`\`\`tsx
451
- import { TanStackRouterDevtoolsInProd } from '@tanstack/react-router-devtools'
452
- \`\`\`
453
-
454
- ## Using inside of the \`RouterProvider\`
455
-
456
- The easiest way for the devtools to work is to render them inside of your root route (or any other route). This will automatically connect the devtools to the router instance.
457
-
458
- \`\`\`tsx
459
- const rootRoute = createRootRoute({
460
- component: () => (
461
- <>
462
- <Outlet />
463
- <TanStackRouterDevtools />
464
- </>
465
- ),
466
- })
467
-
468
- const routeTree = rootRoute.addChildren([
469
- // ... other routes
470
- ])
471
-
472
- const router = createRouter({
473
- routeTree,
474
- })
475
-
476
- function App() {
477
- return <RouterProvider router={router} />
478
- }
479
- \`\`\`
480
-
481
- ## Manually passing the Router Instance
482
-
483
- If rendering the devtools inside of the \`RouterProvider\` isn't your cup of tea, a \`router\` prop for the devtools accepts the same \`router\` instance you pass to the \`Router\` component. This makes it possible to place the devtools anywhere on the page, not just inside the provider:
484
-
485
- \`\`\`tsx
486
- function App() {
487
- return (
488
- <>
489
- <RouterProvider router={router} />
490
- <TanStackRouterDevtools router={router} />
491
- </>
492
- )
493
- }
494
- \`\`\`
495
-
496
- ## Floating Mode
497
-
498
- Floating Mode will mount the devtools as a fixed, floating element in your app and provide a toggle in the corner of the screen to show and hide the devtools. This toggle state will be stored and remembered in localStorage across reloads.
499
-
500
- Place the following code as high in your React app as you can. The closer it is to the root of the page, the better it will work!
501
-
502
- \`\`\`js
503
- import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
504
-
505
- function App() {
506
- return (
507
- <>
508
- <Router />
509
- <TanStackRouterDevtools initialIsOpen={false} />
510
- </>
511
- )
512
- }
513
- \`\`\`
514
-
515
- ## Fixed Mode
516
-
517
- To control the position of the devtools, import the \`TanStackRouterDevtoolsPanel\`:
518
-
519
- \`\`\`js
520
- import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
521
- \`\`\`
522
-
523
- It can then be attached to provided shadow DOM target:
524
-
525
- \`\`\`js
526
- <TanStackRouterDevtoolsPanel
527
- shadowDOMTarget={shadowContainer}
528
- router={router}
529
- />
530
- \`\`\`
531
-
532
- Click [here](https://tanstack.com/router/latest/docs/framework/react/examples/basic-devtools-panel) to see a live example of this in StackBlitz.
533
-
534
- ### Options
535
-
536
- - \`router: Router\`
537
- - The router instance to connect to
538
- - \`initialIsOpen: Boolean\`
539
- - Set this \`true\` if you want the devtools to default to being open
540
- - \`panelProps: PropsObject\`
541
- - Use this to add props to the panel. For example, you can add \`className\`, \`style\` (merge and override default style), etc.
542
- - \`closeButtonProps: PropsObject\`
543
- - Use this to add props to the close button. For example, you can add \`className\`, \`style\` (merge and override default style), \`onClick\` (extend default handler), etc.
544
- - \`toggleButtonProps: PropsObject\`
545
- - Use this to add props to the toggle button. For example, you can add \`className\`, \`style\` (merge and override default style), \`onClick\` (extend default handler), etc.
546
- - \`position?: "top-left" | "top-right" | "bottom-left" | "bottom-right"\`
547
- - Defaults to \`bottom-left\`
548
- - The position of the TanStack Router logo to open and close the devtools panel
549
- - \`shadowDOMTarget?: ShadowRoot\`
550
- - Specifies a Shadow DOM target for the devtools.
551
- - By default, devtool styles are applied to the \`<head>\` tag of the main document (light DOM). When a \`shadowDOMTarget\` is provided, styles will be applied within this Shadow DOM instead.
552
-
553
- ## Embedded Mode
554
-
555
- Embedded Mode will embed the devtools as a regular component in your application. You can style it however you'd like after that!
556
-
557
- \`\`\`js
558
- import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
559
-
560
- function App() {
561
- return (
562
- <>
563
- <Router router={router} />
564
- <TanStackRouterDevtoolsPanel
565
- router={router}
566
- style={styles}
567
- className={className}
568
- />
569
- </>
570
- )
571
- }
572
- \`\`\`
573
-
574
- ### Options
575
-
576
- Use these options to style the devtools.
577
-
578
- - \`style: StyleObject\`
579
- - The standard React style object used to style a component with inline styles
580
- - \`className: string\`
581
- - The standard React className property used to style a component with classes
582
-
583
- # Migration from React Router Checklist
584
-
585
- **_If your UI is blank, open the console, and you will probably have some errors that read something along the lines of \`cannot use 'useNavigate' outside of context\` . This means there are React Router api’s that are still imported and referenced that you need to find and remove. The easiest way to make sure you find all React Router imports is to uninstall \`react-router-dom\` and then you should get typescript errors in your files. Then you will know what to change to a \`@tanstack/react-router\` import._**
586
-
587
- Here is the [example repo](https://github.com/Benanna2019/SickFitsForEveryone/tree/migrate-to-tanstack/router/React-Router)
588
-
589
- - [ ] Install Router - \`npm i @tanstack/react-router\`
590
- - [ ] **Optional:** Uninstall React Router to get TypeScript errors on imports.
591
- - At this point I don’t know if you can do a gradual migration, but it seems likely you could have multiple router providers, not desirable.
592
- - The api’s between React Router and TanStack Router are very similar and could most likely be handled in a sprint cycle or two if that is your companies way of doing things.
593
- - [ ] Create Routes for each existing React Router route we have
594
- - [ ] Create root route
595
- - [ ] Create router instance
596
- - [ ] Add global module in main.tsx
597
- - [ ] Remove any React Router (\`createBrowserRouter\` or \`BrowserRouter\`), \`Routes\`, and \`Route\` Components from main.tsx
598
- - [ ] **Optional:** Refactor \`render\` function for custom setup/providers - The repo referenced above has an example - This was necessary in the case of Supertokens. Supertoken has a specific setup with React Router and a different setup with all other React implementations
599
- - [ ] Set RouterProvider and pass it the router as the prop
600
- - [ ] Replace all instances of React Router \`Link\` component with \`@tanstack/react-router\` \`Link\` component
601
- - [ ] Add \`to\` prop with literal path
602
- - [ ] Add \`params\` prop, where necessary with params like so \`params={{ orderId: order.id }}\`
603
- - [ ] Replace all instances of React Router \`useNavigate\` hook with \`@tanstack/react-router\` \`useNavigate\` hook
604
- - [ ] Set \`to\` property and \`params\` property where needed
605
- - [ ] Replace any React Router \`Outlet\`'s with the \`@tanstack/react-router\` equivalent
606
- - [ ] If you are using \`useSearchParams\` hook from React Router, move the search params default value to the validateSearch property on a Route definition.
607
- - [ ] Instead of using the \`useSearchParams\` hook, use \`@tanstack/react-router\` \`Link\`'s search property to update the search params state
608
- - [ ] To read search params you can do something like the following
609
- - \`const { page } = useSearch({ from: productPage.fullPath })\`
610
- - [ ] If using React Router’s \`useParams\` hook, update the import to be from \`@tanstack/react-router\` and set the \`from\` property to the literal path name where you want to read the params object from
611
- - So say we have a route with the path name \`orders/$orderid\`.
612
- - In the \`useParams\` hook we would set up our hook like so: \`const params = useParams({ from: "/orders/$orderId" })\`
613
- - Then wherever we wanted to access the order id we would get it off of the params object \`params.orderId\`
614
-
615
- # Migration from React Location
616
-
617
- Before you begin your journey in migrating from React Location, it's important that you have a good understanding of the [Routing Concepts](../routing/routing-concepts.md) and [Design Decisions](../decisions-on-dx.md) used by TanStack Router.
618
-
619
- ## Differences between React Location and TanStack Router
620
-
621
- React Location and TanStack Router share much of same design decisions concepts, but there are some key differences that you should be aware of.
622
-
623
- - React Location uses _generics_ to infer types for routes, while TanStack Router uses _module declaration merging_ to infer types.
624
- - Route configuration in React Location is done using a single array of route definitions, while in TanStack Router, route configuration is done using a tree of route definitions starting with the [root route](../routing/routing-concepts.md#the-root-route).
625
- - [File-based routing](../routing/file-based-routing.md) is the recommended way to define routes in TanStack Router, while React Location only allows you to define routes in a single file using a code-based approach.
626
- - TanStack Router does support a [code-based approach](../routing/code-based-routing.md) to defining routes, but it is not recommended for most use cases. You can read more about why, over here: [why is file-based routing the preferred way to define routes?](../decisions-on-dx.md#3-why-is-file-based-routing-the-preferred-way-to-define-routes)
627
-
628
- ## Migration guide
629
-
630
- In this guide we'll go over the process of migrating the [React Location Basic example](https://github.com/TanStack/router/tree/react-location/examples/basic) over to TanStack Router using file-based routing, with the end goal of having the same functionality as the original example (styling and other non-routing related code will be omitted).
631
-
632
- > [!TIP]
633
- > To use a code-based approach for defining your routes, you can read the [code-based Routing](../routing/code-based-routing.md) guide.
634
-
635
- ### Step 1: Swap over to TanStack Router's dependencies
636
-
637
- First, we need to install the dependencies for TanStack Router.
638
-
639
- \`\`\`sh
640
- npm install @tanstack/react-router @tanstack/router-devtools
641
- \`\`\`
642
-
643
- And remove the React Location dependencies.
644
-
645
- \`\`\`sh
646
- npm uninstall @tanstack/react-location @tanstack/react-location-devtools
647
- \`\`\`
648
-
649
- ### Step 2: Use the file-based routing watcher
650
-
651
- If your project uses Vite (or one of the supported bundlers), you can use the TanStack Router plugin to watch for changes in your routes files and automatically update the routes configuration.
652
-
653
- Installation of the Vite plugin:
654
-
655
- \`\`\`sh
656
- npm install -D @tanstack/router-plugin
657
- \`\`\`
658
-
659
- And add it to your \`vite.config.js\`:
660
-
661
- \`\`\`js
662
- import { defineConfig } from 'vite'
663
- import react from '@vitejs/plugin-react'
664
- import { tanstackRouter } from '@tanstack/router-plugin/vite'
665
-
666
- export default defineConfig({
667
- // ...
668
- plugins: [tanstackRouter(), react()],
669
- })
670
- \`\`\`
671
-
672
- However, if your application does not use Vite, you use one of our other [supported bundlers](../routing/file-based-routing.md#getting-started-with-file-based-routing), or you can use the \`@tanstack/router-cli\` package to watch for changes in your routes files and automatically update the routes configuration.
673
-
674
- ### Step 3: Add the file-based configuration file to your project
675
-
676
- Create a \`tsr.config.json\` file in the root of your project with the following content:
677
-
678
- \`\`\`json
679
- {
680
- "routesDirectory": "./src/routes",
681
- "generatedRouteTree": "./src/routeTree.gen.ts"
682
- }
683
- \`\`\`
684
-
685
- You can find the full list of options for the \`tsr.config.json\` file [here](../routing/file-based-routing.md#options).
686
-
687
- ### Step 4: Create the routes directory
688
-
689
- Create a \`routes\` directory in the \`src\` directory of your project.
690
-
691
- \`\`\`sh
692
- mkdir src/routes
693
- \`\`\`
694
-
695
- ### Step 5: Create the root route file
696
-
697
- \`\`\`tsx
698
- // src/routes/__root.tsx
699
- import { createRootRoute, Outlet, Link } from '@tanstack/react-router'
700
- import { TanStackRouterDevtools } from '@tanstack/router-devtools'
701
-
702
- export const Route = createRootRoute({
703
- component: () => {
704
- return (
705
- <>
706
- <div>
707
- <Link to="/" activeOptions={{ exact: true }}>
708
- Home
709
- </Link>
710
- <Link to="/posts">Posts</Link>
711
- </div>
712
- <hr />
713
- <Outlet />
714
- <TanStackRouterDevtools />
715
- </>
716
- )
717
- },
718
- })
719
- \`\`\`
720
-
721
- ### Step 6: Create the index route file
722
-
723
- \`\`\`tsx
724
- // src/routes/index.tsx
725
- import { createFileRoute } from '@tanstack/react-router'
726
-
727
- export const Route = createFileRoute({
728
- component: Index,
729
- })
730
- \`\`\`
731
-
732
- > You will need to move any related components and logic needed for the index route from the \`src/index.tsx\` file to the \`src/routes/index.tsx\` file.
733
-
734
- ### Step 7: Create the posts route file
735
-
736
- \`\`\`tsx
737
- // src/routes/posts.tsx
738
- import { createFileRoute, Link, Outlet } from '@tanstack/react-router'
739
-
740
- export const Route = createFileRoute({
741
- component: Posts,
742
- loader: async () => {
743
- const posts = await fetchPosts()
744
- return {
745
- posts,
746
- }
747
- },
748
- })
749
-
750
- function Posts() {
751
- const { posts } = Route.useLoaderData()
752
- return (
753
- <div>
754
- <nav>
755
- {posts.map((post) => (
756
- <Link
757
- key={post.id}
758
- to={\`/posts/$postId\`}
759
- params={{ postId: post.id }}
760
- >
761
- {post.title}
762
- </Link>
763
- ))}
764
- </nav>
765
- <Outlet />
766
- </div>
767
- )
768
- }
769
- \`\`\`
770
-
771
- > You will need to move any related components and logic needed for the posts route from the \`src/index.tsx\` file to the \`src/routes/posts.tsx\` file.
772
-
773
- ### Step 8: Create the posts index route file
774
-
775
- \`\`\`tsx
776
- // src/routes/posts.index.tsx
777
- import { createFileRoute } from '@tanstack/react-router'
778
-
779
- export const Route = createFileRoute({
780
- component: PostsIndex,
781
- })
782
- \`\`\`
783
-
784
- > You will need to move any related components and logic needed for the posts index route from the \`src/index.tsx\` file to the \`src/routes/posts.index.tsx\` file.
785
-
786
- ### Step 9: Create the posts id route file
787
-
788
- \`\`\`tsx
789
- // src/routes/posts.$postId.tsx
790
- import { createFileRoute } from '@tanstack/react-router'
791
-
792
- export const Route = createFileRoute({
793
- component: PostsId,
794
- loader: async ({ params: { postId } }) => {
795
- const post = await fetchPost(postId)
796
- return {
797
- post,
798
- }
799
- },
800
- })
801
-
802
- function PostsId() {
803
- const { post } = Route.useLoaderData()
804
- // ...
805
- }
806
- \`\`\`
807
-
808
- > You will need to move any related components and logic needed for the posts id route from the \`src/index.tsx\` file to the \`src/routes/posts.$postId.tsx\` file.
809
-
810
- ### Step 10: Generate the route tree
811
-
812
- If you are using one of the supported bundlers, the route tree will be generated automatically when you run the dev script.
813
-
814
- If you are not using one of the supported bundlers, you can generate the route tree by running the following command:
815
-
816
- \`\`\`sh
817
- npx tsr generate
818
- \`\`\`
819
-
820
- ### Step 11: Update the main entry file to render the Router
821
-
822
- Once you've generated the route-tree, you can then update the \`src/index.tsx\` file to create the router instance and render it.
823
-
824
- \`\`\`tsx
825
- // src/index.tsx
826
- import React from 'react'
827
- import ReactDOM from 'react-dom'
828
- import { createRouter, RouterProvider } from '@tanstack/react-router'
829
-
830
- // Import the generated route tree
831
- import { routeTree } from './routeTree.gen'
832
-
833
- // Create a new router instance
834
- const router = createRouter({ routeTree })
835
-
836
- // Register the router instance for type safety
837
- declare module '@tanstack/react-router' {
838
- interface Register {
839
- router: typeof router
840
- }
841
- }
842
-
843
- const domElementId = 'root' // Assuming you have a root element with the id 'root'
844
-
845
- // Render the app
846
- const rootElement = document.getElementById(domElementId)
847
- if (!rootElement) {
848
- throw new Error(\`Element with id \${domElementId} not found\`)
849
- }
850
-
851
- ReactDOM.createRoot(rootElement).render(
852
- <React.StrictMode>
853
- <RouterProvider router={router} />
854
- </React.StrictMode>,
855
- )
856
- \`\`\`
857
-
858
- ### Finished!
859
-
860
- You should now have successfully migrated your application from React Location to TanStack Router using file-based routing.
861
-
862
- React Location also has a few more features that you might be using in your application. Here are some guides to help you migrate those features:
863
-
864
- - [Search params](../guide/search-params.md)
865
- - [Data loading](../guide/data-loading.md)
866
- - [History types](../guide/history-types.md)
867
- - [Wildcard / Splat / Catch-all routes](../routing/routing-concepts.md#splat--catch-all-routes)
868
- - [Authenticated routes](../guide/authenticated-routes.md)
869
-
870
- TanStack Router also has a few more features that you might want to explore:
871
-
872
- - [Router Context](../guide/router-context.md)
873
- - [Preloading](../guide/preloading.md)
874
- - [Pathless Layout Routes](../routing/routing-concepts.md#pathless-layout-routes)
875
- - [Route masking](../guide/route-masking.md)
876
- - [SSR](../guide/ssr.md)
877
- - ... and more!
878
-
879
- If you are facing any issues or have any questions, feel free to ask for help in the TanStack Discord.
880
-
881
- # Frequently Asked Questions
882
-
883
- Welcome to the TanStack Router FAQ! Here you'll find answers to common questions about the TanStack Router. If you have a question that isn't answered here, please feel free to ask in the [TanStack Discord](https://tlinz.com/discord).
884
-
885
- ## Should I commit my \`routeTree.gen.ts\` file into git?
886
-
887
- Yes! Although the route tree file (i.e. \`routeTree.gen.ts\`) is generated by the TanStack Router, it is essentially towards the runtime of your application. It is not a build artifact. The route tree file is a critical part of your application's source code, and it is used by the TanStack Router to build your application's routes at runtime.
888
-
889
- You should commit this file into git so that other developers can use it to build your application.
890
-
891
- ## Can I conditionally render the Root Route component?
892
-
893
- No, the root route is always rendered as it is the entry point of your application.
894
-
895
- If you need to conditionally render a route's component, this usually means that the page content needs to be different based on some condition (e.g. user authentication). For this use case, you should use a [Layout Route](../routing/routing-concepts.md#layout-routes) or a [Pathless Layout Route](../routing/routing-concepts.md#pathless-layout-routes) to conditionally render the content.
896
-
897
- You can restrict access to these routes using a conditional check in the \`beforeLoad\` function of the route.
898
-
899
- <details>
900
- <summary>What does this look like?</summary>
901
-
902
- \`\`\`tsx
903
- // src/routes/_pathless-layout.tsx
904
- import { createFileRoute, Outlet } from '@tanstack/react-router'
905
- import { isAuthenticated } from '../utils/auth'
906
-
907
- export const Route = createFileRoute('/_pathless-layout', {
908
- beforeLoad: async () => {
909
- // Check if the user is authenticated
910
- const authed = await isAuthenticated()
911
- if (!authed) {
912
- // Redirect the user to the login page
913
- return '/login'
914
- }
915
- },
916
- component: PathlessLayoutRouteComponent,
917
- // ...
918
- })
919
-
920
- function PathlessLayoutRouteComponent() {
921
- return (
922
- <div>
923
- <h1>You are authed</h1>
924
- <Outlet />
925
- </div>
926
- )
927
- }
928
- \`\`\`
929
-
930
- </details>
931
-
932
- `;