URL Params & Query
useParams
This hook returns all the parameters for the current route as an object. The default parameter type is
undefined | string | string[]
, but you can optionally provide a type argument to narrow the parameters and types that are returned.import {useParams} from "blitz"const params = useParams()// ReturnType: Record<string, undefined | string | string[]>const params = useParams("string")// ReturnType: Record<string, string>const params = useParams("number")// ReturnType: Record<string, number>const params = useParams("array")// ReturnType: Record<string, string[]>
Example Usage
// File: app/products/pages/products/[id].tsx// URL: /products/2import {useParams} from "blitz"const params = useParams()// params = {id: "2"}
// File: app/pages/blog/[category]/[...slug].tsx// URL: /blog/tech/2020/1import {useParams} from "blitz"const params = useParams()// params = {category: "tech", slug: ["2020", "1"]}const params = useParams("string")// params = {category: "tech"}const params = useParams("array")// params = {slug: ["2020", "1"]}
useParam
This hook return a single parameters for the current route. The default return type is
undefined | string | string[]
, but you can optionally provide a type argument to cast the return type.import {useParam} from "blitz"const param = useParam("id")// ReturnType: undefined | string | string[]const param = useParam("id", "string")// ReturnType: stringconst param = useParam("id", "number")// ReturnType: numberconst param = useParam("id", "array")// ReturnType: string[]
Example Usage
// File: app/locations/pages/locations/[id]/[[...zipcode]].tsx// URL: /locations/2/02137import {useParam} from "blitz"const id = useParam("id", "number")// id = 2const zipcodes = useParam("zipcode", "array")// zipcodes = ["02137"]
// File: app/pages/blog/[slug].tsx// URL: /blog/hello-worldimport {useParam} from "blitz"const slug = useParam("slug", "string")// slug = "hello-world"
useRouterQuery
This hook returns all the query parameters from the URL as an object. Parameter type is always
string
.// URL: /products?sort=asc&limit=10import {useRouterQuery} from "blitz"const query = useRouterQuery()// query = {sort: "asc", limit: "10"}