Communitygithub.com

UI-Komponenten-Muster

Erstelle wiederverwendbare, wartbare UI-Komponenten nach modernen Designmustern. Verwende dies beim Erstellen von Komponentenbibliotheken, bei der Implementierung von Designsystemen oder beim Aufbau skalierbarer Frontend-Architekturen. Behandelt React-Muster, Komposition, Prop-Design, TypeScript und Komponenten-Best-Practices.

Was ist UI-Komponenten-Muster?

Dieses Skill vermittelt ein umfassendes Toolkit zur Erstellung professioneller, skalierbarer UI-Komponenten mit React und TypeScript. Es deckt die wichtigsten Entwurfsmuster ab: durchdachtes Props-API-Design für Benutzerfreundlichkeit und Erweiterbarkeit, das Kompositionsmuster (Compound Components) zum Kombinieren kleinerer Bausteine zu komplexen Oberflächen, Render Props für flexible Anpassungen, die Auslagerung von Geschäftslogik in benutzerdefinierte Hooks und Performance-Optimierung mit React.memo, useMemo und useCallback. Der Skill ist plattformunabhängig für Claude, ChatGPT und Gemini geeignet und richtet sich an Entwickler, die Komponentenbibliotheken aufbauen, Designsysteme umsetzen oder bestehende Oberflächen refaktorieren möchten. Die Anleitung ist praxisnah mit vollständigen Codebeispielen für Button, Card, Dropdown, Modal, Accordion und polymorphe Komponenten, ergänzt durch klare Regeln und Verbote (z.B. kein Props-Drilling über 5 Ebenen, keine Geschäftslogik in UI-Komponenten).

Funktioniert mit✓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

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Vorschau

Aus dem Skill-README

UI-Komponenten-Muster preview

Dokumentation

Was macht UI-Komponenten-Muster?

Wann dieses Skill verwenden

  • Erstellen von Komponentenbibliotheken: Wiederverwendbare UI-Komponenten entwickeln
  • Implementieren von Designsystemen: Konsistente UI-Muster anwenden
  • Komplexe UI: Komponenten mit mehreren Varianten (Button, Modal, Dropdown)
  • Refactoring: Doppelten Code in Komponenten auslagern

Anleitung

Schritt 1: Props-API-Design

Entwerfe Props, die einfach zu verwenden und erweiterbar sind.

Prinzipien:

  • Klare Namen
  • Sinnvolle Standardwerte
  • Typdefinitionen mit TypeScript
  • Optionale Props mit optionalem Marker (?)

Beispiel (Button):

interface ButtonProps {
  // Erforderlich
  children: React.ReactNode;

  // Optional (mit Standardwerten)
  variant?: 'primary' | 'secondary' | 'outline' | 'ghost';
  size?: 'sm' | 'md' | 'lg';
  disabled?: boolean;
  isLoading?: boolean;

  // Event-Handler
  onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;

  // HTML-Attributvererbung
  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>
  );
}

// Anwendungsbeispiel
<Button variant="primary" size="lg" onClick={() => alert('Geklickt!')}>
  Klick mich
</Button>

Schritt 2: Kompositionsmuster

Kombiniere kleine Komponenten, um komplexe UIs zu erstellen.

Beispiel (Card):

// Card-Komponente (Container)
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>;
}

// Compound-Component-Muster
Card.Header = CardHeader;
Card.Body = CardBody;
Card.Footer = CardFooter;

export default Card;

// Verwendung
import Card from './Card';

function ProductCard() {
  return (
    <Card>
      <Card.Header>
        <h3>Produktname</h3>
      </Card.Header>
      <Card.Body>
        <img src="..." alt="Produkt" />
        <p>Produktbeschreibung hier...</p>
      </Card.Body>
      <Card.Footer>
        <button>In den Warenkorb</button>
      </Card.Footer>
    </Card>
  );
}

Schritt 3: Render Props / Children als Funktion

Ein Muster für flexible Anpassungen.

Beispiel (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 || 'Auswählen...'}
      </button>

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

// Verwendung
interface User {
  id: string;
  name: string;
  avatar: string;
}

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

  return (
    <Dropdown
      items={users}
      placeholder="Benutzer auswählen"
      renderItem={(user) => (
        <div className="user-item">
          <img src={user.avatar} alt={user.name} />
          <span>{user.name}</span>
        </div>
      )}
      onSelect={(user) => console.log('Ausgewählt:', user)}
    />
  );
}

Schritt 4: Trennung der Logik mit benutzerdefinierten Hooks

Trenne UI von Geschäftslogik.

Beispiel (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="Schließen">×</button>
        </div>
        <div className="modal-body">{children}</div>
      </div>
    </div>
  );
}

// Verwendung
function App() {
  const { isOpen, open, close } = useModal();

  return (
    <>
      <button onClick={open}>Modal öffnen</button>
      <Modal isOpen={isOpen} onClose={close} title="Mein Modal">
        <p>Modal-Inhalt hier...</p>
      </Modal>
    </>
  );
}

Schritt 5: Leistungsoptimierung

Verhindere unnötige Neurenderings.

React.memo:

// ❌ Schlecht: Child rendert bei jedem Parent-Rendern neu
function ExpensiveComponent({ data }) {
  console.log('Rendere...');
  return <div>{/* Komplexe UI */}</div>;
}

// ✅ Gut: Rendert nur neu, wenn sich Props ändern
const ExpensiveComponent = React.memo(({ data }) => {
  console.log('Rendere...');
  return <div>{/* Komplexe UI */}</div>;
});

useMemo & useCallback:

function ProductList({ products, category }: { products: Product[]; category: string }) {
  // ✅ Gefilterte Ergebnisse merken
  const filteredProducts = useMemo(() => {
    return products.filter(p => p.category === category);
  }, [products, category]);

  // ✅ Callback merken
  const handleAddToCart = useCallback((productId: string) => {
    // In den Warenkorb legen
    console.log('Hinzufügen:', 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)}>In den Warenkorb</button>
    </div>
  );
});

Ausgabeformat

Komponenten-Dateistruktur

components/
├── Button/
│   ├── Button.tsx           # Hauptkomponente
│   ├── Button.test.tsx      # Tests
│   ├── Button.stories.tsx   # Storybook
│   ├── Button.module.css    # Stile
│   └── index.ts             # Export
├── Card/
│   ├── Card.tsx
│   ├── CardHeader.tsx
│   ├── CardBody.tsx
│   ├── CardFooter.tsx
│   └── index.ts
└── Modal/
    ├── Modal.tsx
    ├── useModal.ts          # Benutzerdefinierter Hook
    └── index.ts

Komponenten-Vorlage

import React from 'react';

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

/**
 * Komponentenbeschreibung
 *
 * @example
 * ```tsx
 * <Component>Hallo</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;

Einschränkungen

Erforderliche Regeln (MÜSSEN)

  1. Single-Responsibility-Prinzip: Eine Komponente hat nur eine Rolle

    • Button behandelt nur Buttons, Form behandelt nur Formulare
  2. Props-Typ-Definition: TypeScript-Interface erforderlich

    • Ermöglicht Auto-Vervollständigung
    • Typsicherheit
  3. Barrierefreiheit: aria-*, role, tabindex, etc.

Verbotene Regeln (DÜRFEN NICHT)

  1. Übermäßiges Props-Drilling: Verboten bei 5+ Ebenen Tiefe

    • Context oder Composition verwenden
  2. Keine Geschäftslogik: API-Aufrufe und komplexe Berechnungen in UI-Komponenten verbieten

    • In benutzerdefinierte Hooks auslagern
  3. Inline-Objekte/Funktionen: Leistungsverschlechterung

    // ❌ Schlechtes Beispiel
    <Component style={{ color: 'red' }} onClick={() => handleClick()} />
    
    // ✅ Gutes Beispiel
    const style = { color: 'red' };
    const handleClick = useCallback(() => {...}, []);
    <Component style={style} onClick={handleClick} />
    

Beispiele

Beispiel 1: Accordion (Compound Component)

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

// Zustand mit Context teilen
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 muss innerhalb von Accordion verwendet werden');

  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;

// Verwendung
<Accordion>
  <Accordion.Item index={0} title="Abschnitt 1">
    Inhalt für Abschnitt 1
  </Accordion.Item>
  <Accordion.Item index={1} title="Abschnitt 2">
    Inhalt für Abschnitt 2
  </Accordion.Item>
</Accordion>

Beispiel 2: Polymorphe Komponente (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>;
}

// Verwendung
<Text>Standard-Span</Text>
<Text as="h1">Überschrift 1</Text>
<Text as="p" style={{ color: 'blue' }}>Absatz</Text>
<Text as={Link} href="/about">Link</Text>

Best Practices

  1. Komposition vor Props: Kinderkomponenten statt vieler Props nutzen
  2. Controlled vs Uncontrolled: Je nach Situation wählen
  3. Standard-Props: Sinnvolle Standardwerte bereitstellen
  4. Storybook: Komponentendokumentation und -entwicklung

Referenzen

Metadaten

Version

  • Aktuelle Version: 1.0.0
  • Zuletzt aktualisiert: 2025-01-01
  • Kompatible Plattformen: Claude, ChatGPT, Gemini

Verwandte Skills

Tags

#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

Verwandte Skills