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

README.md.ejs

558 lines16.4 KB

1Welcome to your new TanStack app!
2​
3# Getting Started
4​
5To run this application:
6​
7```bash
8<%= packageManager %> install
9<%= getPackageManagerRunScript('start') %>
10```
11​
12# Building For Production
13​
14To build this application for production:
15​
16```bash
17<%= getPackageManagerRunScript('build') %>
18```
19​
20## Testing
21​
22This project uses [Vitest](https://vitest.dev/) for testing. You can run the tests with:
23​
24```bash
25<%= getPackageManagerRunScript('test') %>
26```
27​
28## Styling
29<% if (tailwind) { %>
30This project uses [Tailwind CSS](https://tailwindcss.com/) for styling.
31<% } else { %>
32This project uses CSS for styling.
33<% } %>
34<% if (addOnEnabled.biome || addOnEnabled.eslint) { %>
35## Linting & Formatting
36<% if (addOnEnabled.biome) { %>
37This project uses [Biome](https://biomejs.dev/) for linting and formatting. The following scripts are available:
38<% } %>
39<% if (addOnEnabled.eslint) { %>
40This project uses [eslint](https://eslint.org/) and [prettier](https://prettier.io/) for linting and formatting. Eslint is configured using [tanstack/eslint-config](https://tanstack.com/config/latest/docs/eslint). The following scripts are available:
41<% } %>
42```bash
43<%= getPackageManagerRunScript('lint') %>
44<%= getPackageManagerRunScript('format') %>
45<%= getPackageManagerRunScript('check') %>
46```
47<% } %>
48<% for(const addon of addOns.filter(addon => addon.readme)) { %>
49<%- addon.readme %>
50<% } %>
51​
52## Routing
53<% if (fileRouter) { %>This project uses [TanStack Router](https://tanstack.com/router). The initial setup is a file based router. Which means that the routes are managed as files in `src/routes`.<% } else { %>This project uses [TanStack Router](https://tanstack.com/router). The initial setup is a code based router. Which means that the routes are defined in code (in the `./src/main.<%= jsx %>` file). If you like you can also use a file based routing setup by following the [File Based Routing](https://tanstack.com/router/latest/docs/framework/react/guide/file-based-routing) guide.<% } %>
54​
55### Adding A Route
56<% if (fileRouter) { %>
57To add a new route to your application just add another a new file in the `./src/routes` directory.
58​
59TanStack will automatically generate the content of the route file for you.
60<% } else { %>
61To add a new route to your application just add another `createRoute` call to the `./src/main.<%= jsx %>` file. The example below adds a new `/about`route to the root route.
62​
63```tsx
64const aboutRoute = createRoute({
65 getParentRoute: () => rootRoute,
66 path: "/about",
67 component: () => <h1>About</h1>,
68});
69```
70​
71You will also need to add the route to the `routeTree` in the `./src/main.<%= jsx %>` file.
72​
73```tsx
74const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]);
75```
76​
77With this set up you should be able to navigate to `/about` and see the about page.
78​
79Of course you don't need to implement the About page in the `main.<%= jsx %>` file. You can create that component in another file and import it into the `main.<%= jsx %>` file, then use it in the `component` property of the `createRoute` call, like so:
80​
81```tsx
82import About from "./components/About.<%= jsx %>";
83​
84const aboutRoute = createRoute({
85 getParentRoute: () => rootRoute,
86 path: "/about",
87 component: About,
88});
89```
90​
91That is how we have the `App` component set up with the home page.
92​
93For more information on the options you have when you are creating code based routes check out the [Code Based Routing](https://tanstack.com/router/latest/docs/framework/react/guide/code-based-routing) documentation.
94<% } %>
95Now that you have two routes you can use a `Link` component to navigate between them.
96​
97### Adding Links
98​
99To use SPA (Single Page Application) navigation you will need to import the `Link` component from `@tanstack/react-router`.
100​
101```tsx
102import { Link } from "@tanstack/react-router";
103```
104​
105Then anywhere in your JSX you can use it like so:
106​
107```tsx
108<Link to="/about">About</Link>
109```
110​
111This will create a link that will navigate to the `/about` route.
112​
113More information on the `Link` component can be found in the [Link documentation](https://tanstack.com/router/v1/docs/framework/react/api/router/linkComponent).
114​
115### Using A Layout
116​
117<% if (codeRouter) { %>
118Layouts can be used to wrap the contents of the routes in menus, headers, footers, etc.
119​
120There is already a layout in the `src/main.<%= jsx %>` file:
121​
122```tsx
123const rootRoute = createRootRoute({
124 component: () => (
125 <>
126 <Outlet />
127 <TanStackRouterDevtools />
128 </>
129 ),
130});
131```
132​
133You can use the React component specified in the `component` property of the `rootRoute` to wrap the contents of the routes. The `<Outlet />` component is used to render the current route within the body of the layout. For example you could add a header to the layout like so:
134​
135```tsx
136import { Link } from "@tanstack/react-router";
137​
138const rootRoute = createRootRoute({
139 component: () => (
140 <>
141 <header>
142 <nav>
143 <Link to="/">Home</Link>
144 <Link to="/about">About</Link>
145 </nav>
146 </header>
147 <Outlet />
148 <TanStackRouterDevtools />
149 </>
150 ),
151});
152```
153<% } else { %>In the File Based Routing setup the layout is located in `src/routes/__root.tsx`. Anything you add to the root route will appear in all the routes. The route content will appear in the JSX where you use the `<Outlet />` component.
154​
155Here is an example layout that includes a header:
156​
157```tsx
158import { Outlet, createRootRoute } from '@tanstack/react-router'
159import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
160​
161import { Link } from "@tanstack/react-router";
162​
163export const Route = createRootRoute({
164 component: () => (
165 <>
166 <header>
167 <nav>
168 <Link to="/">Home</Link>
169 <Link to="/about">About</Link>
170 </nav>
171 </header>
172 <Outlet />
173 <TanStackRouterDevtools />
174 </>
175 ),
176})
177```
178<% } %>
179The `<TanStackRouterDevtools />` component is not required so you can remove it if you don't want it in your layout.
180​
181More information on layouts can be found in the [Layouts documentation](https://tanstack.com/router/latest/docs/framework/react/guide/routing-concepts#layouts).
182​
183<% if (codeRouter) { %>
184### Migrating To File Base Routing
185​
186First you need to add the Vite plugin for Tanstack Router:
187​
188```bash
189<%= getPackageManagerAddScript("@tanstack/router-plugin", true) %>
190```
191​
192From there you need to update your `vite.config.js` file to use the plugin:
193​
194```ts
195import { defineConfig } from "vite";
196import viteReact from "@vitejs/plugin-react";
197import { TanStackRouterVite } from "@tanstack/router-plugin/vite";<% if (tailwind) { %>
198import tailwindcss from "@tailwindcss/vite";
199<% } %>
201// https://vitejs.dev/config/
202export default defineConfig({
203 plugins: [
204 TanStackRouterVite(),
205 viteReact()<% if (tailwind) { %>,
206 tailwindcss()<% } %>
207 ],
208});
209```
210​
211Now you'll need to rearrange your files a little bit. That starts with creating a `routes` directory in the `src` directory:
212​
213```bash
214mkdir src/routes
215```
216​
217Then you'll need to create a `src/routes/__root.<%= jsx %>` file with the contents of the root route that was in `main.<%= jsx %>`.
218​
219```tsx
220import { Outlet, createRootRoute } from "@tanstack/react-router";
221import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
222​
223export const Route = createRootRoute({
224 component: () => (
225 <>
226 <Outlet />
227 <TanStackRouterDevtools />
228 </>
229 ),
230});
231```
232​
233Next up you'll need to move your home route code into `src/routes/index.<%= jsx %>`
234​
235```tsx
236import { createFileRoute } from "@tanstack/react-router";
237​
238import logo from "../logo.svg";
239import "../App.css";
240​
241export const Route = createFileRoute("/")({
242 component: App,
243});
244​
245function App() {
246 return (<% if (tailwind) { %>
247 <div className="text-center">
248 <header className="min-h-screen flex flex-col items-center justify-center bg-[#282c34] text-white text-[calc(10px+2vmin)]">
249 <img
250 src={logo}
251 className="h-[40vmin] pointer-events-none animate-[spin_20s_linear_infinite]"
252 alt="logo"
253 />
254 <p>
255 Edit <code>src/App.tsx</code> and save to reload.
256 </p>
257 <a
258 className="text-[#61dafb] hover:underline"
259 href="https://reactjs.org"
260 target="_blank"
261 rel="noopener noreferrer"
262 >
263 Learn React
264 </a>
265 <a
266 className="text-[#61dafb] hover:underline"
267 href="https://tanstack.com"
268 target="_blank"
269 rel="noopener noreferrer"
270 >
271 Learn TanStack
272 </a>
273 </header>
274 </div>
275<% } else { %>
276 <div className="App">
277 <header className="App-header">
278 <img src={logo} className="App-logo" alt="logo" />
279 <p>
280 Edit <code>src/App.tsx</code> and save to reload.
281 </p>
282 <a
283 className="App-link"
284 href="https://reactjs.org"
285 target="_blank"
286 rel="noopener noreferrer"
287 >
288 Learn React
289 </a>
290 <a
291 className="App-link"
292 href="https://tanstack.com"
293 target="_blank"
294 rel="noopener noreferrer"
295 >
296 Learn TanStack
297 </a>
298 </header>
299 </div>
300<% } %> );
302```
303​
304At this point you can delete `src/App.<%= jsx %>`, you will no longer need it as the contents have moved into `src/routes/index.<%= jsx %>`.
305​
306The only additional code is the `createFileRoute` function that tells TanStack Router where to render the route. Helpfully the Vite plugin will keep the path argument that goes to `createFileRoute` automatically in sync with the file system.
307​
308Finally the `src/main.<%= jsx %>` file can be simplified down to this:
309​
310```tsx
311import { StrictMode } from "react";
312import ReactDOM from "react-dom/client";
313import { RouterProvider, createRouter } from "@tanstack/react-router";
314​
315// Import the generated route tree
316import { routeTree } from "./routeTree.gen";
317​
318import "./styles.css";
319import reportWebVitals from "./reportWebVitals.<%= js %>";
320​
321// Create a new router instance
322const router = createRouter({
323 routeTree,
324 defaultPreload: "intent",
325 defaultPreloadStaleTime: 0,
326 scrollRestoration: true,
327 defaultStructuralSharing: true
328});
329<% if (typescript) { %>
330// Register the router instance for type safety
331declare module "@tanstack/react-router" {
332 interface Register {
333 router: typeof router;
334 }
336​
337// Render the app
338const rootElement = document.getElementById("app")!;
339<% } else { %>
340// Render the app
341const rootElement = document.getElementById("app");
342<% } %>if (!rootElement.innerHTML) {
343 const root = ReactDOM.createRoot(rootElement);
344 root.render(
345 <StrictMode>
346 <RouterProvider router={router} />
347 </StrictMode>
348 );
350​
351// If you want to start measuring performance in your app, pass a function
352// to log results (for example: reportWebVitals(console.log))
353// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
354reportWebVitals();
355```
356​
357Now you've got a file based routing setup in your project! Let's have some fun with it! Just create a file in `about.<%= jsx %>` in `src/routes` and it if the application is running TanStack will automatically add contents to the file and you'll have the start of your `/about` route ready to go with no additional work. You can see why folks find File Based Routing so easy to use.
358​
359You can find out everything you need to know on how to use file based routing in the [File Based Routing](https://tanstack.com/router/latest/docs/framework/react/guide/file-based-routing) documentation.
360<% } %>
361## Data Fetching
362​
363There are multiple ways to fetch data in your application. You can use TanStack Query to fetch data from a server. But you can also use the `loader` functionality built into TanStack Router to load the data for a route before it's rendered.
364​
365For example:
366​
367```tsx
368const peopleRoute = createRoute({
369 getParentRoute: () => rootRoute,
370 path: "/people",
371 loader: async () => {
372 const response = await fetch("https://swapi.dev/api/people");<% if (typescript) { %>
373 return response.json() as Promise<{
374 results: {
375 name: string;
376 }[];
377 }>;
378<% } else { %>
379 return response.json();
380<% } %> },
381 component: () => {
382 const data = peopleRoute.useLoaderData();
383 return (
384 <ul>
385 {data.results.map((person) => (
386 <li key={person.name}>{person.name}</li>
387 ))}
388 </ul>
389 );
390 },
391});
392```
393​
394Loaders simplify your data fetching logic dramatically. Check out more information in the [Loader documentation](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#loader-parameters).
395​
396### React-Query
397​
398React-Query is an excellent addition or alternative to route loading and integrating it into you application is a breeze.
399​
400First add your dependencies:
401​
402```bash
403<%= getPackageManagerAddScript("@tanstack/react-query @tanstack/react-query-devtools") %>
404```
405​
406Next we'll need to create a query client and provider. We recommend putting those in `main.<%= jsx %>`.
407​
408```tsx
409import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
410​
411// ...
412​
413const queryClient = new QueryClient();
414​
415// ...
416​
417if (!rootElement.innerHTML) {
418 const root = ReactDOM.createRoot(rootElement);
419​
420 root.render(
421 <QueryClientProvider client={queryClient}>
422 <RouterProvider router={router} />
423 </QueryClientProvider>
424 );
426```
427​
428You can also add TanStack Query Devtools to the root route (optional).
429​
430```tsx
431import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
432​
433const rootRoute = createRootRoute({
434 component: () => (
435 <>
436 <Outlet />
437 <ReactQueryDevtools buttonPosition="top-right" />
438 <TanStackRouterDevtools />
439 </>
440 ),
441});
442```
443​
444Now you can use `useQuery` to fetch your data.
445​
446```tsx
447import { useQuery } from "@tanstack/react-query";
448​
449import "./App.css";
450​
451function App() {
452 const { data } = useQuery({
453 queryKey: ["people"],
454 queryFn: () =>
455 fetch("https://swapi.dev/api/people")
456 .then((res) => res.json())<% if (typescript) { %>
457 .then((data) => data.results as { name: string }[]),
458<% } else { %>
459 .then((data) => data.results),
460<% } %> initialData: [],
461 });
462​
463 return (
464 <div>
465 <ul>
466 {data.map((person) => (
467 <li key={person.name}>{person.name}</li>
468 ))}
469 </ul>
470 </div>
471 );
473​
474export default App;
475```
476​
477You can find out everything you need to know on how to use React-Query in the [React-Query documentation](https://tanstack.com/query/latest/docs/framework/react/overview).
478​
479## State Management
480​
481Another common requirement for React applications is state management. There are many options for state management in React. TanStack Store provides a great starting point for your project.
482​
483First you need to add TanStack Store as a dependency:
484​
485```bash
486<%= getPackageManagerAddScript("@tanstack/store") %>
487```
488​
489Now let's create a simple counter in the `src/App.<%= jsx %>` file as a demonstration.
490​
491```tsx
492import { useStore } from "@tanstack/react-store";
493import { Store } from "@tanstack/store";
494import "./App.css";
495​
496const countStore = new Store(0);
497​
498function App() {
499 const count = useStore(countStore);
500 return (
501 <div>
502 <button onClick={() => countStore.setState((n) => n + 1)}>
503 Increment - {count}
504 </button>
505 </div>
506 );
508​
509export default App;
510```
511​
512One of the many nice features of TanStack Store is the ability to derive state from other state. That derived state will update when the base state updates.
513​
514Let's check this out by doubling the count using derived state.
515​
516```tsx
517import { useStore } from "@tanstack/react-store";
518import { Store, Derived } from "@tanstack/store";
519import "./App.css";
520​
521const countStore = new Store(0);
522​
523const doubledStore = new Derived({
524 fn: () => countStore.state * 2,
525 deps: [countStore],
526});
527doubledStore.mount();
528​
529function App() {
530 const count = useStore(countStore);
531 const doubledCount = useStore(doubledStore);
532​
533 return (
534 <div>
535 <button onClick={() => countStore.setState((n) => n + 1)}>
536 Increment - {count}
537 </button>
538 <div>Doubled - {doubledCount}</div>
539 </div>
540 );
542​
543export default App;
544```
545​
546We use the `Derived` class to create a new store that is derived from another store. The `Derived` class has a `mount` method that will start the derived store updating.
547​
548Once we've created the derived store we can use it in the `App` component just like we would any other store using the `useStore` hook.
549​
550You can find out everything you need to know on how to use TanStack Store in the [TanStack Store documentation](https://tanstack.com/store/latest).
551​
552# Demo files
553​
554Files prefixed with `demo` can be safely deleted. They are there to provide a starting point for you to play around with the features you've installed.
555​
556# Learn More
557​
558You can learn more about all of the offerings from TanStack in the [TanStack documentation](https://tanstack.com).