Communitygithub.com

ComeOnOliver/skillshub - UIコンポーネントパターン

再利用可能で保守性の高いUIコンポーネントを、最新のデザインパターンに従って構築します。コンポーネントライブラリの作成、デザインシステムの実装、またはスケーラブルなフロントエンドアーキテクチャの構築に使用します。Reactパターン、コンポジション、プロップ設計、TypeScript、およびコンポーネントのベストプラクティスを扱います。

skillshub - UIコンポーネントパターン とは?

このスキルは、最新のフロントエンド開発(特にReactとTypeScript)において、再利用可能で保守性が高く、スケーラブルなUIコンポーネントを構築するための包括的なガイドです。コンポーネントライブラリの作成やデザインシステムの実装を支援し、開発者が一貫性のある高品質なUIを効率的に構築できるように設計されています。主にClaude、ChatGPT、GeminiなどのAIエージェントプラットフォームと連携して使用されることを想定しており、自然言語での指示を通じて具体的なコード生成や設計アドバイスを提供します。このスキルは、プロップAPIの設計、コンポジションパターン、レンダープロップ、カスタムフックによるロジックの分離、パフォーマンス最適化といった5つのステップに従って、実践的なコード例とともにベストプラクティスを解説します。単一責任の原則、TypeScriptによる型安全性、アクセシビリティ対応を必須ルールとし、過剰なプロップドリリングやUIコンポーネント内でのビジネスロジックの記述を禁止することで、クリーンで保守しやすいコードベースを維持します。アコーディオン(複合コンポーネント)やポリモーフィックコンポーネントなどの実践例も含まれており、特定のUIライブラリに依存しない汎用的な知識を提供するため、様々なプロジェクトに適用可能です。

対応✓Claude Code~Codex CLI~Cursor✓Gemini CLI
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/supercent-io/ui-component-patterns

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

プレビュー

スキル README より

skillshub - UIコンポーネントパターン preview

ドキュメント

UIコンポーネントパターン

このスキルを使用するタイミング

  • コンポーネントライブラリの構築: 再利用可能なUIコンポーネントの作成
  • デザインシステムの実装: 一貫性のあるUIパターンの適用
  • 複雑なUI: 複数のバリアントを必要とするコンポーネント(Button、Modal、Dropdown)
  • リファクタリング: 重複コードをコンポーネントに抽出

手順

ステップ1: Props APIの設計

使いやすく拡張可能なPropsを設計します。

原則:

  • 明確な名前
  • 妥当なデフォルト値
  • TypeScriptによる型定義
  • オプションのPropsにはオプションマーカー(?)を使用

例 (Button):

interface ButtonProps {
  // 必須
  children: React.ReactNode;

  // オプション(デフォルト値あり)
  variant?: 'primary' | 'secondary' | 'outline' | 'ghost';
  size?: 'sm' | 'md' | 'lg';
  disabled?: boolean;
  isLoading?: boolean;

  // イベントハンドラ
  onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;

  // HTML属性の継承
  type?: 'button' | 'submit' | 'reset';
  className?: string;
}

function Button({
  children,
  variant = 'primary',
  size = 'md',
  disabled = false,
  isLoading = false,
  onClick,
  type = 'button',
  className = '',
  ...rest
}: ButtonProps) {
  const baseClasses = 'btn';
  const variantClasses = `btn-${variant}`;
  const sizeClasses = `btn-${size}`;
  const classes = `${baseClasses} ${variantClasses} ${sizeClasses} ${className}`;

  return (
    <button
      type={type}
      className={classes}
      disabled={disabled || isLoading}
      onClick={onClick}
      {...rest}
    >
      {isLoading ? <Spinner /> : children}
    </button>
  );
}

// 使用例
<Button variant="primary" size="lg" onClick={() => alert('Clicked!')}>
  Click Me
</Button>

ステップ2: コンポジションパターン

小さなコンポーネントを組み合わせて複雑なUIを構築します。

例 (Card):

// Cardコンポーネント(コンテナ)
interface CardProps {
  children: React.ReactNode;
  className?: string;
}

function Card({ children, className = '' }: CardProps) {
  return <div className={`card ${className}`}>{children}</div>;
}

// Card.Header
function CardHeader({ children }: { children: React.ReactNode }) {
  return <div className="card-header">{children}</div>;
}

// Card.Body
function CardBody({ children }: { children: React.ReactNode }) {
  return <div className="card-body">{children}</div>;
}

// Card.Footer
function CardFooter({ children }: { children: React.ReactNode }) {
  return <div className="card-footer">{children}</div>;
}

// 複合コンポーネントパターン
Card.Header = CardHeader;
Card.Body = CardBody;
Card.Footer = CardFooter;

export default Card;

// 使用例
import Card from './Card';

function ProductCard() {
  return (
    <Card>
      <Card.Header>
        <h3>Product Name</h3>
      </Card.Header>
      <Card.Body>
        <img src="..." alt="Product" />
        <p>Product description here...</p>
      </Card.Body>
      <Card.Footer>
        <button>Add to Cart</button>
      </Card.Footer>
    </Card>
  );
}

ステップ3: レンダープロップ / 関数としての子要素

柔軟なカスタマイズのためのパターン。

例 (Dropdown):

interface DropdownProps<T> {
  items: T[];
  renderItem: (item: T, index: number) => React.ReactNode;
  onSelect: (item: T) => void;
  placeholder?: string;
}

function Dropdown<T>({ items, renderItem, onSelect, placeholder }: DropdownProps<T>) {
  const [isOpen, setIsOpen] = useState(false);
  const [selected, setSelected] = useState<T | null>(null);

  const handleSelect = (item: T) => {
    setSelected(item);
    onSelect(item);
    setIsOpen(false);
  };

  return (
    <div className="dropdown">
      <button onClick={() => setIsOpen(!isOpen)}>
        {selected ? renderItem(selected, -1) : placeholder || 'Select...'}
      </button>

      {isOpen && (
        <ul className="dropdown-menu">
          {items.map((item, index) => (
            <li key={index} onClick={() => handleSelect(item)}>
              {renderItem(item, index)}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

// 使用例
interface User {
  id: string;
  name: string;
  avatar: string;
}

function UserDropdown() {
  const users: User[] = [...];

  return (
    <Dropdown
      items={users}
      placeholder="Select a user"
      renderItem={(user) => (
        <div className="user-item">
          <img src={user.avatar} alt={user.name} />
          <span>{user.name}</span>
        </div>
      )}
      onSelect={(user) => console.log('Selected:', user)}
    />
  );
}

ステップ4: カスタムフックによるロジックの分離

UIとビジネスロジックを分離します。

例 (Modal):

// hooks/useModal.ts
function useModal(initialOpen = false) {
  const [isOpen, setIsOpen] = useState(initialOpen);

  const open = useCallback(() => setIsOpen(true), []);
  const close = useCallback(() => setIsOpen(false), []);
  const toggle = useCallback(() => setIsOpen(prev => !prev), []);

  return { isOpen, open, close, toggle };
}

// components/Modal.tsx
interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  title: string;
  children: React.ReactNode;
}

function Modal({ isOpen, onClose, title, children }: ModalProps) {
  if (!isOpen) return null;

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h2>{title}</h2>
          <button onClick={onClose} aria-label="Close">×</button>
        </div>
        <div className="modal-body">{children}</div>
      </div>
    </div>
  );
}

// 使用例
function App() {
  const { isOpen, open, close } = useModal();

  return (
    <>
      <button onClick={open}>Open Modal</button>
      <Modal isOpen={isOpen} onClose={close} title="My Modal">
        <p>Modal content here...</p>
      </Modal>
    </>
  );
}

ステップ5: パフォーマンス最適化

不要な再レンダリングを防ぎます。

React.memo:

// ❌ 悪い例: 親が再レンダリングされるたびに子も再レンダリングされる
function ExpensiveComponent({ data }) {
  console.log('Rendering...');
  return <div>{/* Complex UI */}</div>;
}

// ✅ 良い例: propsが変更されたときのみ再レンダリング
const ExpensiveComponent = React.memo(({ data }) => {
  console.log('Rendering...');
  return <div>{/* Complex UI */}</div>;
});

useMemo & useCallback:

function ProductList({ products, category }: { products: Product[]; category: string }) {
  // ✅ フィルタリング結果をメモ化
  const filteredProducts = useMemo(() => {
    return products.filter(p => p.category === category);
  }, [products, category]);

  // ✅ コールバックをメモ化
  const handleAddToCart = useCallback((productId: string) => {
    // Add to cart
    console.log('Adding:', productId);
  }, []);

  return (
    <div>
      {filteredProducts.map(product => (
        <ProductCard
          key={product.id}
          product={product}
          onAddToCart={handleAddToCart}
        />
      ))}
    </div>
  );
}

const ProductCard = React.memo(({ product, onAddToCart }) => {
  return (
    <div>
      <h3>{product.name}</h3>
      <button onClick={() => onAddToCart(product.id)}>Add to Cart</button>
    </div>
  );
});

出力形式

コンポーネントファイル構造

components/
├── Button/
│   ├── Button.tsx           # メインコンポーネント
│   ├── Button.test.tsx      # テスト
│   ├── Button.stories.tsx   # Storybook
│   ├── Button.module.css    # スタイル
│   └── index.ts             # エクスポート
├── Card/
│   ├── Card.tsx
│   ├── CardHeader.tsx
│   ├── CardBody.tsx
│   ├── CardFooter.tsx
│   └── index.ts
└── Modal/
    ├── Modal.tsx
    ├── useModal.ts          # カスタムフック
    └── index.ts

コンポーネントテンプレート

import React from 'react';

export interface ComponentProps {
  // Props定義
  children: React.ReactNode;
  className?: string;
}

/**
 * コンポーネントの説明
 *
 * @example
 * ```tsx
 * <Component>Hello</Component>
 * ```
 */
export const Component = React.forwardRef<HTMLDivElement, ComponentProps>(
  ({ children, className = '', ...rest }, ref) => {
    return (
      <div ref={ref} className={`component ${className}`} {...rest}>
        {children}
      </div>
    );
  }
);

Component.displayName = 'Component';

export default Component;

制約

必須ルール(必ず守ること)

  1. 単一責任の原則: 1つのコンポーネントは1つの役割のみを持つ

    • Buttonはボタンのみ、Formはフォームのみを扱う
  2. Props型定義: TypeScriptインターフェース必須

    • 自動補完を有効にする
    • 型安全性を確保する
  3. アクセシビリティ: aria-*、role、tabindexなど

禁止ルール(絶対にやってはいけないこと)

  1. 過剰なPropsドリリング: 5階層以上は禁止

    • ContextまたはCompositionを使用する
  2. ビジネスロジックの混入: UIコンポーネントでのAPI呼び出しや複雑な計算は禁止

    • カスタムフックに分離する
  3. インラインのオブジェクト/関数: パフォーマンス低下

    // ❌ 悪い例
    <Component style={{ color: 'red' }} onClick={() => handleClick()} />
    
    // ✅ 良い例
    const style = { color: 'red' };
    const handleClick = useCallback(() => {...}, []);
    <Component style={style} onClick={handleClick} />
    

例

例1: アコーディオン(複合コンポーネント)

import React, { createContext, useContext, useState } from 'react';

// Contextで状態を共有
const AccordionContext = createContext<{
  activeIndex: number | null;
  setActiveIndex: (index: number | null) => void;
} | null>(null);

function Accordion({ children }: { children: React.ReactNode }) {
  const [activeIndex, setActiveIndex] = useState<number | null>(null);

  return (
    <AccordionContext.Provider value={{ activeIndex, setActiveIndex }}>
      <div className="accordion">{children}</div>
    </AccordionContext.Provider>
  );
}

function AccordionItem({ index, title, children }: {
  index: number;
  title: string;
  children: React.ReactNode;
}) {
  const context = useContext(AccordionContext);
  if (!context) throw new Error('AccordionItem must be used within Accordion');

  const { activeIndex, setActiveIndex } = context;
  const isActive = activeIndex === index;

  return (
    <div className="accordion-item">
      <button
        className="accordion-header"
        onClick={() => setActiveIndex(isActive ? null : index)}
        aria-expanded={isActive}
      >
        {title}
      </button>
      {isActive && <div className="accordion-body">{children}</div>}
    </div>
  );
}

Accordion.Item = AccordionItem;
export default Accordion;

// 使用例
<Accordion>
  <Accordion.Item index={0} title="Section 1">
    Content for section 1
  </Accordion.Item>
  <Accordion.Item index={1} title="Section 2">
    Content for section 2
  </Accordion.Item>
</Accordion>

例2: ポリモーフィックコンポーネント(as prop)

type PolymorphicComponentProps<C extends React.ElementType> = {
  as?: C;
  children: React.ReactNode;
} & React.ComponentPropsWithoutRef<C>;

function Text<C extends React.ElementType = 'span'>({
  as,
  children,
  ...rest
}: PolymorphicComponentProps<C>) {
  const Component = as || 'span';
  return <Component {...rest}>{children}</Component>;
}

// 使用例
<Text>Default span</Text>
<Text as="h1">Heading 1</Text>
<Text as="p" style={{ color: 'blue' }}>Paragraph</Text>
<Text as={Link} href="/about">Link</Text>

ベストプラクティス

  1. 多くのPropsよりもComposition: 多くのPropsの代わりにchildrenを活用する
  2. 制御コンポーネント vs 非制御コンポーネント: 状況に応じて選択する
  3. デフォルトProps: 妥当なデフォルト値を提供する
  4. Storybook: コンポーネントのドキュメント化と開発

参考

メタデータ

バージョン

  • 現在のバージョン: 1.0.0
  • 最終更新日: 2025-01-01
  • 互換性のあるプラットフォーム: Claude, ChatGPT, Gemini

関連スキル

タグ

#UI-components #React #design-patterns #composition #TypeScript #frontend

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

関連スキル