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/1234
https://example.com/sku/1234/detail
https://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
Groups
In some cases you would like to move your routes into a subdirectory without affecting the pathname which qwik city is generating based on the folder structure. Or you have several routes on the same level which should use different layouts. In this case you can create directories in parentheses (eg. (products)
). Let's have a look at an example:
src/
βββ routes/
βββ (product)/
βββ detail/
| βββindex.tsx
βββ preview/
| βββindex.tsx
βββ promotion/
βββindex.tsx
The above structure will match:
https://example.com/detail
https://example.com/preview
https://example.com/promotion
Note that product
is not part of the pathname.