読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
種類の選択肢は、リンクで書けます。
// src/components/CategoryLinks.tsx
import Link from "next/link";
export const CategoryLinks = () => (
<nav aria-label="種類で絞り込む">
<Link href="/products">すべて</Link>
<Link href="/products?category=bread">食事パン</Link>
<Link href="/products?category=pastry">菓子パン</Link>
<Link href="/products?category=savory">総菜パン</Link>
<Link href="/products?category=sweets">菓子</Link>
</nav>
);
<select> のように、操作の途中で URL を変えたいときは、Client Components で useRouter を使います。
"use client";
import { useRouter, useSearchParams } from "next/navigation";
export const SortSelect = () => {
const router = useRouter();
const searchParams = useSearchParams();
const handleChange = (order: string) => {
const next = new URLSearchParams(searchParams);
next.set("order", order);
router.replace(`/products?${next.toString()}`, { scroll: false });
};
return (
<select value={searchParams.get("order") ?? "default"} onChange={(e) => handleChange(e.target.value)}>
<option value="default">おすすめ順</option>
<option value="priceAsc">価格の安い順</option>
</select>
);
};
| 書き方 | 使う場面 |
|---|---|
Link | 選択肢をリンクとして並べる |
router.push | 履歴に残し、戻るボタンで前の表示に戻れるようにする |
router.replace | 履歴に残さず、今の URL を置きかえる |
useSearchParams は開いた URL によって値が変わるため、これを使う部品は、ページの中で Suspense に包んで置きます。
11 / 16