Route Parameters
Route Parameters are parts of the URLs that are extracted into parameters.
Imagine that you have a page with the following URLs where [skuId] can be any of the thousands of products that you have in your database. It would be impractical to create a route for each product. Instead, we need to define a Route Parameter (a part of the URL) that will be used to extract the [skuId].
https://example.com/sku/[skuId]- Will match:
https://example.com/sku/1234 - Will match:
https://example.com/sku/xyz-567
- Will match:
https://example.com/sku/[skuId]/details- Will match:
https://example.com/sku/1234/details
- Will match:
src/
βββ routes/
βββ sku/
βββ [skuId]/
βββ index.tsx # https://example.com/sku/1234
βββ details/
βββ index.tsx # https://example.com/sku/1234/details
Retrieving the Route Parameter from the URL
Once we have [skuId] in the URL, we need a way to retrieve it. This can be done by using useLocation() API.
import { useLocation } from '@builder.io/qwik-city';
export default component$(() => {
const location = useLocation();
return (
<div>
<h1>SKU</h1>
<p>Pathname: {location.pathname}</p>
<p>Sku Id: {location.params.skuId}</p>
</div>
);
});
Catch All Routes
It is also possible to create a catch-all routes by adding a directory like [...slug]. This works like the above described example but will also consider subsegments of the URI. It can also be applied on the routes root level.
src/
βββ routes/
βββ sku/
βββ [...slug]/
βββ index.tsx
The above structure will match:
https://example.com/sku/1234https://example.com/sku/1234/detailhttps://example.com/sku/1234/detail/edit- etc
It is possible to limit catch-all routes by adding a subdirectory say end-of-route in [...slug] directory.
src/
βββ routes/
βββ sku/
βββ [...slug]/
βββ index.tsx
βββ end-of-route/
βββindex.tsx
The above structure will match:
https://example.com/sku/1234/5678/end-of-route