読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第2節 props の型を作る

2.1 データの型をそのまま渡す

②で作った Product の型を、src/types.ts に置いておきます。

// src/types.ts
export type ProductCategory = "bread" | "pastry" | "savory" | "sweets";

export type Product = {
  id: string;
  name: string;
  price: number;
  category: ProductCategory;
  reservable: boolean;
};
// src/components/ProductCard.tsx
import type { Product } from "../types.ts";

type ProductCardProps = {
  product: Product;
};

export const ProductCard = ({ product }: ProductCardProps) => {
  return (
    <article className="product-card">
      <h3>{product.name}</h3>
      <p>{product.price}円</p>
    </article>
  );
};
<ProductCard product={croissant} />
渡し方長所短所
値を1つずつ渡す部品が Product を知らなくてよい渡す値が増えると長くなる
Product をまとめて渡す短く書ける部品が Product の形に結び付く

商品のカードのように、そのデータを表示するための部品なら、まとめて渡すのが自然です。ボタンのように、どこでも使う部品には、必要な値だけを渡します。

6 / 16