Qwikの主な3つのルート
Qwikにおける3つのルートについて説明したいと思います。
QwikもNext.jsやRemixと同様にroutes直下にディレクトリを作成し、その中にindex.tsx/mdx/mdを作成することで、そこがエントリーポイントとして機能します。
1. ディレクトリ直下のindex.tsx/mdx/md
/
└─ src
└─ routes
├─ layout.tsx
├─ user
│ └─ index.tsx # https://sample.com/user
├─ company
│ └─ index.mdx # https://sample.com/company
└─ product
└─ index.md # https://sample.com/product
最も基本的なルートです。
例えば上記のようにuserディレクトリを作成し、その直下にindex.tsxを作成する場合のルートです。
この場合、ファイル名は必ず「index」から始まる必要があります。
2. 動的セグメント その1
/
└─ src
└─ routes
├─ layout.tsx
└─ user
└─ [name]
└─ index.tsx # https://sample.com/user/[name]
上記例ではroutes直下にuserというディレクトリを作成し、その直下にさらに[name]という形式でディレクトリを作成することで使用できるルートです。[]内は任意に命名できます。
そして、[name]直下にはindex.tsxを作成します。
以下のコードは簡単な使用例です。
https://sample.com/user/johnというURLが叩かれた場合に、johnを取得する場合です。
useLocationを使用してloc.params.nameとします。この場合のnameは自身で命名した[name]のnameになります。
import { component$ } from "@builder.io/qwik";
import { Hello } from "~/components/hello/hello";
import { useLocation } from "@builder.io/qwik-city";
export default component$(() => {
const loc = useLocation();
return (
<Hello name={loc.params.name} />
);
});
3. 動的セグメント その2
/
└─ src
└─ routes
├─ layout.tsx
├─ user
│ └─ [name]
│ └─ index.tsx # https://sample.com/user/[name]
├─ company
│ ├─ [name]
│ │ └─ index.tsx # https://sample.com/company/[name]
│ └─ [...all]
│ └─ index.tsx # https://sample.com/company/ *
└─ [...rest]
└─ index.tsx # You tried a route that doesn't exist.
src/routes/user/[name]/index.tsx → /user/[name]
src/routes/company/[name]/index.tsx → /company/[name]
src/routes/company/[...all]/index.tsx → /company/anything else that didnt match
src/routes/[...rest]/index.tsx → /anything else that didnt match
まずcompany直下の[name]はデータベースに登録されているいずれかに該当するcompanyが存在する場合のルートです。該当するcompanyが存在しない場合は[...all]のルートが呼ばれることになります。
同様にroutes直下に[...rest]ディレクトリを作成した場合のルートです。どのルートにも該当しなかった場合に使用されるルートです。この場合も同様にuseLocation().params.restとすることでクエリパラメータを取得します。
おわりに
以下はRemixのルーティングの例になりますが、userディレクトリ下にinfoやcontact、postなどのルートも配置ができるようになっています。個人的にQwikのディレクトリベースのルーティングの方がシンプルでわかりやすくて良いと感じました。
/
└─ src
└─ routes/
└─ user/
├─ _index.tsx /user
├─ info.tsx /user/info
├─ info.contact.tsx /user/info/contact
└─ post.$id.tsx /user/post/[id]
Discussion