読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
QuantityPicker のファイルの先頭に、"use client" を書きます。
// src/components/QuantityPicker.tsx
"use client";
import { useState } from "react";
export const QuantityPicker = ({ max }: { max: number }) => {
const [quantity, setQuantity] = useState(1);
return (
<div>
<button type="button" onClick={() => setQuantity((q) => Math.max(q - 1, 1))}>-</button>
<span>{quantity}個</span>
<button type="button" onClick={() => setQuantity((q) => Math.min(q + 1, max))}>+</button>
</div>
);
};
// src/app/products/[id]/page.tsx(Server Component)
import { QuantityPicker } from "@/components/QuantityPicker";
export default async function ProductPage({ params }: PageProps<"/products/[id]">) {
const { id } = await params;
const product = await getProduct(id);
if (product === undefined) notFound();
return (
<main>
<h1>{product.name}</h1>
<p>{product.price}円</p>
{product.reservable && <QuantityPicker max={10} />}
</main>
);
}
"use client" は、「このファイルから先は、ブラウザでも動く」という境目の印です。Client Components も、最初はサーバーで HTML になって届き、そのあとブラウザで JavaScript が動いて、ボタンが押せるようになります。
| 比べる点 | Server Components | Client Components |
|---|---|---|
| 書き方 | 何も書かない | ファイルの先頭に "use client" |
| 動く場所 | サーバーだけ | サーバー(最初の HTML)とブラウザ |
| state・イベント | 使えない | 使える |
| データを直接読む | できる | できない |
| ブラウザに送る JavaScript | 増えない | 部品の分だけ増える |
6 / 16