ShadCN UI パターン - 2025年11月基準
使用するタイミング
- 新しい UI コンポーネントの構築
- 既存コンポーネントの ShadCN へのリファクタリング
- バリデーション付きフォームの実装
- モーダル、ダイアログ、オーバーレイの作成
- アクセシビリティ準拠の確保
ShadCN UI を選ぶ理由
- npm ではなくコピペ - コンポーネントコードを完全に所有
- Radix UI プリミティブ - アクセシビリティが組み込み済み(WCAG 2.1 AA 準拠)
- TailwindCSS ファースト - 完全なカスタマイズ、CSS-in-JS 不要
- TypeScript ネイティブ - 型安全なプロパティとバリアント
- Server コンポーネント対応 - Next.js 15 App Router と互換性あり
基本原則
1. コンポーネントのインストールパターン
# 必要なコンポーネントを個別にインストール
npx shadcn@latest add button
npx shadcn@latest add dialog
npx shadcn@latest add form
npx shadcn@latest add input
npx shadcn@latest add label
コンポーネントは src/components/ui/ ディレクトリにコピーされます。コードはあなたが所有します。
2. コンポーネントの使用パターン
Button コンポーネント
import { Button } from "@/components/ui/button"
// ✅ 推奨:意味的なバリアントを使用
<Button variant="default">保存</Button>
<Button variant="destructive">削除</Button>
<Button variant="outline">キャンセル</Button>
<Button variant="ghost">スキップ</Button>
<Button variant="link">詳細を見る</Button>
// ✅ 推奨:サイズバリアントを使用
<Button size="default">中</Button>
<Button size="sm">小</Button>
<Button size="lg">大</Button>
<Button size="icon"><アイコン /></Button>
// ❌ 非推奨:Button コンポーネントを使わずにカスタムボタンを作成
<button className="px-4 py-2 bg-blue-500">悪い例</button>
Dialog/Modal コンポーネント
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
// ✅ 推奨:適切なダイアログ構造を使用(アクセシビリティ)
<Dialog>
<DialogTrigger asChild>
<Button>設定を開く</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>設定</DialogTitle>
<DialogDescription>
ここでアプリケーションの設定を行えます。
</DialogDescription>
</DialogHeader>
{/* ダイアログの内容 */}
</DialogContent>
</Dialog>
// ❌ 非推奨:DialogHeader や DialogTitle を省略(スクリーンリーダーで問題が発生)
<DialogContent>
<h2>設定</h2> {/* 誤り:DialogTitle を使用すべき */}
</DialogContent>
Form コンポーネント(React Hook Form + Zod)
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
// ✅ 推奨:最初に Zod スキーマを定義(バリデーション)
const formSchema = z.object({
email: z.string().email("無効なメールアドレスです"),
password: z.string().min(8, "パスワードは8文字以上である必要があります"),
})
function LoginForm() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
email: "",
password: "",
},
})
async function onSubmit(values: z.infer<typeof formSchema>) {
// 型安全なバリデーション済みデータ
console.log(values)
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>メールアドレス</FormLabel>
<FormControl>
<Input placeholder="[email protected]" {...field} />
</FormControl>
<FormDescription>
メールアドレスは第三者と共有されません。
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>パスワード</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">サインイン</Button>
</form>
</Form>
)
}
// ❌ 非推奨:バリデーションなしで非制御フォームを使用
<form>
<input name="email" /> {/* バリデーションなし */}
</form>
3. Server コンポーネント vs Client コンポーネント
// ✅ 推奨:静的なダイアログには Server コンポーネントを使用
import { Dialog, DialogContent } from "@/components/ui/dialog"
export default function ServerDialog() {
// 'use client' は不要
return <Dialog>...</Dialog>
}
// ✅ 推奨:状態が必要な場合は Client コンポーネントを使用
'use client'
import { useState } from 'react'
import { Dialog, DialogContent } from "@/components/ui/dialog"
export function ClientDialog() {
const [open, setOpen] = useState(false)
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>...</DialogContent>
</Dialog>
)
}
4. アクセシビリティ要件
フォーカス管理
// ✅ 推奨:適切なフォーカス管理のために asChild を指定して DialogTrigger を使用
<DialogTrigger asChild>
<Button>開く</Button>
</DialogTrigger>
// ❌ 非推奨:適切なフォーカス処理なしで手動でトリガー
<Button onClick={() => setOpen(true)}>開く</Button>
キーボードナビゲーション
// ✅ ShadCN が自動的に処理:
// - ESC でダイアログを閉じる
// - Tab でフォーカス可能な要素間を移動
// - Enter/Space でボタンを起動
// - 矢印キーでメニューを移動
// ❌ 非推奨:正当な理由なくデフォルトのキーボード動作を上書き
スクリーンリーダーサポート
// ✅ 推奨:常に DialogTitle を含める(ARIA 必須)
<DialogHeader>
<DialogTitle>プロジェクトを削除</DialogTitle>
<DialogDescription>
この操作は元に戻せません。
</DialogDescription>
</DialogHeader>
// ❌ 非推奨:誤った方法で視覚的に隠されたタイトルを使用
<DialogTitle className="sr-only">削除</DialogTitle>
// 明確な視覚的な代替手段がある場合のみ非表示にしてください
5. よく使うコンポーネント
| コンポーネント | ユースケース | 主要なプロパティ |
|---|---|---|
Button | すべてのクリック可能な操作 | variant, size, asChild |
Dialog | モーダル、確認画面 | open, onOpenChange |
Sheet | サイドパネル、ドロワー | side, open, onOpenChange |
Popover | ツールチップ、メニュー | open, onOpenChange |
Form | すべてのフォーム | form (useForm から) |
Input | テキスト入力 | type, placeholder |
Select | ドロップダウン | value, onValueChange |
Checkbox | ブール値の入力 | checked, onCheckedChange |
RadioGroup | 単一選択 | value, onValueChange |
Table | データテーブル | table (TanStack Table から) |
Card | コンテンツコンテナ | CardHeader, CardContent, CardFooter |
Toast | 通知 | title, description, variant |
Command | コマンドパレット | onSelect |
Tabs | タブナビゲーション | value, onValueChange |
6. TailwindCSS のベストプラクティス
// ✅ 推奨:Tailwind ユーティリティクラスを使用
<Button className="w-full mt-4">送信</Button>
// ✅ 推奨:条件付きクラスには cn() ヘルパーを使用
import { cn } from "@/lib/utils"
<Button className={cn(
"w-full",
isLoading && "opacity-50 cursor-not-allowed"
)}>
送信
</Button>
// ❌ 非推奨:インラインスタイルを使用
<Button style={{ width: '100%', marginTop: '16px' }}>送信</Button>
// ❌ 非推非推奨:コンポーネント用のカスタム CSS ファイルを作成
/* styles.css */
.my-button { width: 100%; }
7. ダークモード対応
// ✅ 推奨:Tailwind のダークモードクラスを使用
<div className="bg-white dark:bg-gray-900 text-black dark:text-white">
コンテンツ
</div>
// ✅ ShadCN コンポーネントはダークモードが組み込み済み
<Button variant="default">
{/* ダークモードで自動的にスタイル適用 */}
</Button>
よくある間違いをチェック
❌ DialogTitle の欠落(アクセシビリティ違反)
// 悪い例
<DialogContent>
<h2>設定</h2>
<p>コンテンツ</p>
</DialogContent>
// 良い例
<DialogContent>
<DialogHeader>
<DialogTitle>設定</DialogTitle>
</DialogHeader>
<p>コンテンツ</p>
</DialogContent>
❌ フォームに Form コンポーネントを使用していない
// 悪い例 - バリデーションなし、UX が悪い
<form>
<input name="email" />
<button type="submit">送信</button>
</form>
// 良い例 - バリデーション、エラーメッセージ、アクセシビリティ
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<FormField name="email" ... />
</form>
</Form>
❌ バリアントを使用せずに色をハードコーディング
// 悪い例
<Button className="bg-red-500 hover:bg-red-600">削除</Button>
// 良い例
<Button variant="destructive">削除</Button>
❌ トリガーに asChild を使用していない
// 悪い例 - 不要なネストされたボタンを作成
<DialogTrigger>
<Button>開く</Button>
</DialogTrigger>
// レンダリング結果: <button><button>開く</button></button> (無効な HTML)
// 良い例 - プロパティを単一のボタンに統合
<DialogTrigger asChild>
<Button>開く</Button>
</DialogTrigger>
// レンダリング結果: <button>開く</button>
ShadCN コンポーネントのテスト
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Dialog, DialogTrigger, DialogContent } from '@/components/ui/dialog'
describe('Dialog', () => {
it('トリガーがクリックされたときに開くこと', async () => {
const user = userEvent.setup()
render(
<Dialog>
<DialogTrigger asChild>
<button>開く</button>
</DialogTrigger>
<DialogContent>
<div>ダイアログの内容</div>
</DialogContent>
</Dialog>
)
// 初期状態ではダイアログの内容は表示されていない
expect(screen.queryByText('ダイアログの内容')).not.toBeInTheDocument()
// トリガーをクリック
await user.click(screen.getByText('開く'))
// ダイアログの内容が表示される
expect(screen.getByText('ダイアログの内容')).toBeInTheDocument()
})
it('ESC キーで閉じること', async () => {
const user = userEvent.setup()
render(
<Dialog defaultOpen>
<DialogContent>ダイアログの内容</DialogContent>
</Dialog>
)
expect(screen.getByText('ダイアログの内容')).toBeInTheDocument()
await user.keyboard('{Escape}')
expect(screen.queryByText('ダイアログの内容')).not.toBeInTheDocument()
})
})
リソース
- 公式ドキュメント: https://ui.shadcn.com
- Radix UI: https://www.radix-ui.com
- サンプル: https://ui.shadcn.com/examples
- テーマ: https://ui.shadcn.com/themes
2025年11月の注記
ShadCN UI は、2025年11月時点での React コンポーネントライブラリの業界標準です。一貫性、アクセシビリティ、保守性のために、すべての新しい Quetrex アプリケーションは ShadCN UI を使用する必要があります。