Frontend Exercise
Now that we’ve covered the basics of React and TanStack Router, let’s build something!
Objective
Section titled “Objective”Create a new route in your application that displays a “Profile” page. This page should accept a username as a search parameter and display it.
Requirements:
- Create a new file
routes/profile.tsx. - The route should be accessible at
/profile. - It should validate a search parameter named
username(string). - Display “Hello, [username]!” on the page.
- If no username is provided, it should default to “Guest”.
-
Create the Route File Create a new file named
profile.tsxinside yoursrc/routesfolder. -
Define the Search Params Schema Use
zodor a simple validator to define the expected search parameters. -
Create the Component Create a React component that reads the search params using
useSearch. -
Export the Route Export the route using
createFileRoute.
💡 Click to reveal hint
Here is how you might structure src/routes/profile.tsx:
import { createFileRoute } from "@tanstack/react-router";import { z } from "zod";
// 1. Define the search param schemaconst profileSearchSchema = z.object({ username: z.string().optional().default("Guest"),});
export const Route = createFileRoute("/profile")({ // 2. Validate search params validateSearch: (search) => profileSearchSchema.parse(search), component: ProfilePage,});
function ProfilePage() { // 3. Read search params const { username } = Route.useSearch();
return ( <div className="p-4"> <h1 className="text-2xl font-bold">Profile</h1> <p>Hello, {username}!</p> </div> );}Testing
Section titled “Testing”- Save your file. The router generator should automatically update
routeTree.gen.ts. - Navigate to
http://localhost:5173/profile. You should see “Hello, Guest!”. - Navigate to
http://localhost:5173/profile?username=Developer. You should see “Hello, Developer!”.
Next Steps
Section titled “Next Steps”Congratulations! You’ve successfully created a type-safe route with search parameters. This is a core pattern we will use extensively in the Task Manager for filtering and pagination.
Keep exploring! Try adding more search parameters like role or age.