Defining URL Query Parameters with TanStack Config
Show how to define URL query parameters using TanStack Config, ensuring type safety and defining necessary validations.
import { createBrowserRouter, createRoutesFromElements, Route } from 'tanstack-router';
import { parse, stringify } from 'query-string';
Import necessary modules from 'tanstack-router' and 'query-string' for parsing and stringifying query parameters.
const searchRoute = new Route({
path: '/search',
element: '<SearchPage />',
loader: async ({ request }) => {
// Extract query params from URL
const url = new URL(request.url);
const queryParams = parse(url.search);
// Validate and transform queryParams here if necessary
return { queryParams };
}
});
Define a route for '/search'. Use a loader function to extract, parse, and optionally validate or transform query parameters from the URL.
const router = createBrowserRouter(
createRoutesFromElements(
searchRoute
)
);
Create a browser router instance by passing the defined search route. This enables URL-based routing with query parameters in the TanStack Router.