読み方のヒント

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

第2節 共通の部品を作る

2.1 種類を決めて部品にする

ボタンの見た目を、3つの種類と2つの大きさに絞ります。

// src/shared/ui/Button.tsx
import type { ComponentPropsWithoutRef } from "react";
import styles from "./Button.module.css";

type ButtonProps = ComponentPropsWithoutRef<"button"> & {
  variant?: "primary" | "secondary" | "danger";
  size?: "medium" | "small";
};

export const Button = ({
  variant = "primary",
  size = "medium",
  type = "button",
  className,
  ...rest
}: ButtonProps) => {
  return (
    <button
      type={type}
      className={[styles.button, styles[variant], styles[size], className].filter(Boolean).join(" ")}
      {...rest}
    />
  );
};
部分意味
ComponentPropsWithoutRef<"button">&lt;button&gt; が受け取れる属性(onClick・disabled・aria-* など)をすべて受け取る
variant見た目の種類。3つに限る
type = "button"既定を button にし、フォームの中で思わず送信しないようにする
...rest残りの属性を、そのまま &lt;button&gt; に渡す

&lt;button&gt; の属性をそのまま受け取るので、aria-expanded や disabled も、ふつうのボタンと同じように渡せます。React 19 では、ref も props として渡せます。

7 / 17