[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6H8ZC048TZ71178J2KCP8SJ":3,"skill-same:01M6H8ZC048TZ71178J2KCP8SJ":58},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":32,"linkOnly":33,"markdownContent":34,"markdownBody":35,"frontMatter":36,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":14,"repositoryHtmlUrl":40,"repositoryHomepageUrl":6,"ownerHtmlUrl":41,"ownerBlogUrl":6,"ownerDescription":42,"updatedAt":43,"install":44,"resources":57},"01M6H8ZC048TZ71178J2KCP8SJ","components",null,"React component architecture for creating composable, accessible components with data attributes. Use when creating\u002Fupdating composable components, not for higher-level feature\u002Fpage components.","drhazemibclc\u002Fplate","drhazemibclc","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F153584232?v=4","01M6H8X67MYG903V4N92MKWKYK","Hazem Ali Abd Elraouf","01M6H8X6C5TSX21P7HJVZVNFNQ",0,"MIT","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fcomponents\u002FSKILL.md",[],[5,19,20,21,22,23,24,25,26,27,28,29,30,31],"react","component","architecture","composable","component architecture","data","page","use","feature","react component","with","attributes","for","2026-11-10 10:12:30",false,"---\nname: components\ndescription: React component architecture for creating composable, accessible components with data attributes. Use when creating\u002Fupdating composable components, not for higher-level feature\u002Fpage components.\n---\n\n# Accessibility\n\nURL: \u002Faccessibility\n\n\ntitle: Accessibility\ndescription: Building components that are usable by everyone, including users with disabilities who rely on assistive technologies.\n\n\nAccessibility (a11y) is not an optional feature—it's a fundamental requirement for modern web components. Every component must be usable by everyone, including people with visual, motor, auditory, or cognitive disabilities.\n\nThis guide is a non-exhaustive list of accessibility principles and patterns that you should follow when building components. It's not a comprehensive guide, but it should give you a sense of the types of issues you should be aware of.\n\nIf you use a linter with strong accessibility rules like [Ultracite](https:\u002F\u002Fwww.ultracite.ai), these types of issues will likely be caught automatically, but it's still important to understand the principles.\n\n## Core Principles\n\n1. **Semantic HTML First** - Use native elements (`\u003Cbutton>`, `\u003Cnav>`, `\u003Cul>`) for built-in accessibility\n2. **Keyboard Navigation** - Support Tab, Arrow keys, Home\u002FEnd, Escape, Enter\u002FSpace for all interactions\n3. **Screen Reader Support** - Use ARIA attributes (`aria-label`, `aria-current`, `aria-live`) for proper announcements\n4. **Visual Accessibility** - Ensure focus indicators, sufficient contrast (4.5:1), and responsive text sizing\n\n## ARIA Patterns\n\nARIA enhances semantic HTML for assistive technologies. Key rules:\n\n1. Use semantic HTML first, ARIA only when necessary\n2. Don't override native semantics\n3. All interactive elements need keyboard access and accessible names\n\n**Common Attributes:**\n\n- **Roles** - Define element type (`role=\"button\"`, `role=\"navigation\"`, `role=\"alert\"`)\n- **States** - Describe current state (`aria-checked`, `aria-expanded`, `aria-selected`)\n- **Properties** - Provide context (`aria-label`, `aria-describedby`, `aria-controls`, `aria-required`, `aria-invalid`)\n\n## Component Patterns\n\nComplex interactive components require specific accessibility patterns. For detailed implementations, consult [WAI-ARIA Authoring Practices](https:\u002F\u002Fwww.w3.org\u002FWAI\u002FARIA\u002Fapg\u002Fpatterns\u002F).\n\n**Modal\u002FDialog:**\n\n- `role=\"dialog\"`, `aria-modal=\"true\"`, `aria-labelledby`\n- Trap focus with Tab, close with Escape\n- Store and restore previous focus\n- Prevent body scroll when open\n\n**Dropdown Menu:**\n\n- `role=\"menu\"` on container, `role=\"menuitem\"` on items\n- `aria-haspopup=\"true\"`, `aria-expanded`, `aria-controls`\n- Arrow keys navigate, Enter\u002FSpace select, Escape closes\n\n**Tabs:**\n\n- `role=\"tablist\"` on container, `role=\"tab\"` on buttons, `role=\"tabpanel\"` on panels\n- `aria-selected`, `aria-controls`, `aria-labelledby`\n- Arrow Left\u002FRight navigate, Home\u002FEnd jump to first\u002Flast\n- Only active tab is focusable (`tabIndex={0\u002F-1}`)\n\n**Forms:**\n\n- `\u003Clabel htmlFor>` paired with input `id`\n- `aria-required`, `aria-invalid`, `aria-describedby` for validation\n- Error messages with `role=\"alert\"`\n- Group related inputs with `\u003Cfieldset>` and `\u003Clegend>`\n\n## Focus Management\n\n- **Focus Visible** - Use `:focus-visible` for keyboard-only focus indicators\n- **Focus Trapping** - Trap Tab\u002FShift+Tab within modals by cycling between first and last focusable elements\n- **Focus Restoration** - Store `document.activeElement` before opening overlays, restore on close\n\n## Live Regions\n\nAnnounce dynamic content changes to screen readers:\n\n- **Status Messages** - `aria-live=\"polite\"` (waits), `aria-live=\"assertive\"` (interrupts), `role=\"alert\"` for errors\n- **Progress** - `role=\"progressbar\"` with `aria-valuenow`, `aria-valuemin`, `aria-valuemax`, `aria-label`\n\n## Color and Contrast\n\n- **Contrast Ratios** - Normal text: 4.5:1, Large text (≥18pt\u002F14pt bold): 3:1, Non-text (icons, borders): 3:1\n- **Color Independence** - Never use color alone; combine with text, icons, or ARIA attributes\n\n## Mobile Accessibility\n\n- **Touch Targets** - Minimum 44×44px (iOS) or 48×48dp (Android)\n- **Viewport** - Allow zoom (`\u003Cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1\">`)\n\n## Common Pitfalls\n\n1. **Placeholder as Label** - Use persistent `\u003Clabel>`, not disappearing placeholders\n2. **Empty Buttons** - Icon buttons need `aria-label` or visually hidden text\n3. **Disabled Elements** - Use `aria-disabled` instead of `disabled` to keep focusability and explain why\n\n# asChild\n\nURL: \u002Fas-child\n\n\ntitle: asChild\ndescription: How to use the `asChild` prop to render a custom element within the component.\n\n\nThe `asChild` prop is a powerful pattern in modern React component libraries. Popularized by [Radix UI](https:\u002F\u002Fwww.radix-ui.com\u002Fprimitives\u002Fdocs\u002Fguides\u002Fcomposition) and adopted by [shadcn\u002Fui](https:\u002F\u002Fui.shadcn.com), this pattern allows you to replace default markup with custom elements while maintaining the component's functionality.\n\n## Understanding `asChild`\n\nWhen `asChild` is `true`, instead of rendering its default DOM element, the component merges its props, behaviors, and event handlers with its immediate child element.\n\n```tsx\n\u002F\u002F Without asChild: Creates wrapper\n\u003CDialog.Trigger>\u003Cbutton>Open\u003C\u002Fbutton>\u003C\u002FDialog.Trigger>\n\u002F\u002F Output: \u003Cbutton data-state=\"closed\">\u003Cbutton>Open\u003C\u002Fbutton>\u003C\u002Fbutton>\n\n\u002F\u002F With asChild: Merges props\n\u003CDialog.Trigger asChild>\u003Cbutton>Open\u003C\u002Fbutton>\u003C\u002FDialog.Trigger>\n\u002F\u002F Output: \u003Cbutton data-state=\"closed\">Open\u003C\u002Fbutton>\n```\n\n## How It Works\n\nUses `React.cloneElement` to clone the child and merge props (including event handlers) from both parent and child components. The enhanced child is returned with combined functionality.\n\n## Key Benefits\n\n1. **Semantic HTML** - Use the most appropriate element (links for navigation, buttons for actions)\n2. **Clean DOM Structure** - Eliminates wrapper elements and \"wrapper hell\"\n3. **Design System Integration** - Works seamlessly with existing component libraries\n4. **Component Composition** - Compose multiple behaviors onto a single element\n\n## Common Use Cases\n\n- **Custom Triggers** - Replace default triggers with custom components or links\n- **Accessible Navigation** - Maintain semantic navigation elements\n- **Form Integration** - Integrate with form libraries while preserving functionality\n\n## Best Practices\n\n1. **Maintain Accessibility** - Ensure child elements have proper semantics and ARIA attributes\n2. **Document Support** - Use JSDoc to document the `asChild` prop in your component interfaces\n3. **Test Forwarding** - Verify props are properly forwarded to child components\n4. **Handle Edge Cases** - Consider conditional rendering and dynamic children\n\n## Common Pitfalls\n\n1. **Not Spreading Props** - Child components must spread `...props` to receive merged behavior\n2. **Multiple Children** - `asChild` expects exactly one child element, not multiple\n3. **Fragment Children** - Fragments are not valid, use actual HTML elements\n\n# Composition\n\nURL: \u002Fcomposition\n\n\ntitle: Composition\ndescription: The foundation of building modern UI components.\n\n\nComposition, or composability, is the foundation of building modern UI components. It is one of the most powerful techniques for creating flexible, reusable components that can handle complex requirements without sacrificing API clarity.\n\nInstead of cramming all functionality into a single component with dozens of props, composition distributes responsibility across multiple cooperating components.\n\nFernando gave a great talk about this at React Universe Conf 2025, where he shared his approach to rebuilding Slack's Message Composer as a composable component.\n\n\u003CVideo src=\"https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=4KvbVq3Eg5w\" \u002F>\n\n## Making a component composable\n\nTo make a component composable, you need to break it down into smaller, more focused components. For example, let's take this Accordion component:\n\n```tsx title=\"accordion.tsx\"\nimport { Accordion } from '@\u002Fcomponents\u002Fui\u002Faccordion';\n\nconst data = [\n  {\n    title: 'Accordion 1',\n    content: 'Accordion 1 content',\n  },\n  {\n    title: 'Accordion 2',\n    content: 'Accordion 2 content',\n  },\n  {\n    title: 'Accordion 3',\n    content: 'Accordion 3 content',\n  },\n];\n\nreturn \u003CAccordion data={data} \u002F>;\n```\n\nWhile this Accordion component might seem simple, it's handling too many responsibilities. It's responsible for rendering the container, trigger and content; as well as handling the accordion state and data.\n\nCustomizing the styling of this component is difficult because it's tightly coupled. It likely requires global CSS overrides. Additionally, adding new functionality or tweaking the behavior requires modifying the component source code.\n\nTo solve this, we can break this down into smaller, more focused components.\n\n### 1. Root Component\n\nFirst, let's focus on the container - the component that holds everything together i.e. the trigger and content. This container doesn't need to know about the data, but it does need to keep track of the open state.\n\nHowever, we also want this state to be accessible by child components. So, let's use the Context API to create a context for the open state.\n\nFinally, to allow for modification of the `div` element, we'll extend the default HTML attributes.\n\nWe'll call this component the \"Root\" component.\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Faccordion.tsx\"\ntype AccordionProps = React.ComponentProps\u003C'div'> & {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n};\n\nconst AccordionContext = createContext\u003CAccordionProps>({\n  open: false,\n  setOpen: () => {},\n});\n\nexport type AccordionRootProps = React.ComponentProps\u003C'div'> & {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n};\n\nexport const Root = ({ children, open, setOpen, ...props }: AccordionRootProps) => (\n  \u003CAccordionContext.Provider value={{ open, setOpen }}>\n    \u003Cdiv {...props}>{children}\u003C\u002Fdiv>\n  \u003C\u002FAccordionContext.Provider>\n);\n```\n\n### 2. Item Component\n\nThe Item component is the element that contains the accordion item. It is simply a wrapper for each item in the accordion.\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Faccordion.tsx\"\nexport type AccordionItemProps = React.ComponentProps\u003C'div'>;\n\nexport const Item = (props: AccordionItemProps) => \u003Cdiv {...props} \u002F>;\n```\n\n### 3. Trigger Component\n\nThe Trigger component is the element that opens the accordion when activated. It is responsible for:\n\n- Rendering as a button by default (can be customized with `asChild`)\n- Handling click events to open the accordion\n- Managing focus when accordion closes\n- Providing proper ARIA attributes\n\nLet's add this component to our Accordion component.\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Faccordion.tsx\"\nexport type AccordionTriggerProps = React.ComponentProps\u003C'button'> & {\n  asChild?: boolean;\n};\n\nexport const Trigger = ({ asChild, ...props }: AccordionTriggerProps) => (\n  \u003CAccordionContext.Consumer>\n    {({ open, setOpen }) => \u003Cbutton onClick={() => setOpen(!open)} {...props} \u002F>}\n  \u003C\u002FAccordionContext.Consumer>\n);\n```\n\n### 4. Content Component\n\nThe Content component is the element that contains the accordion content. It is responsible for:\n\n- Rendering the content when the accordion is open\n- Providing proper ARIA attributes\n\nLet's add this component to our Accordion component.\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Faccordion.tsx\"\nexport type AccordionContentProps = React.ComponentProps\u003C'div'> & {\n  asChild?: boolean;\n};\n\nexport const Content = ({ asChild, ...props }: AccordionContentProps) => (\n  \u003CAccordionContext.Consumer>{({ open }) => \u003Cdiv {...props} \u002F>}\u003C\u002FAccordionContext.Consumer>\n);\n```\n\n### 5. Putting it all together\n\nNow that we have all the components, we can put them together in our original file.\n\n```tsx title=\"accordion.tsx\"\nimport * as Accordion from '@\u002Fcomponents\u002Fui\u002Faccordion';\n\nconst data = [\n  {\n    title: 'Accordion 1',\n    content: 'Accordion 1 content',\n  },\n  {\n    title: 'Accordion 2',\n    content: 'Accordion 2 content',\n  },\n  {\n    title: 'Accordion 3',\n    content: 'Accordion 3 content',\n  },\n];\n\nreturn (\n  \u003CAccordion.Root open={false} setOpen={() => {}}>\n    {data.map((item) => (\n      \u003CAccordion.Item key={item.title}>\n        \u003CAccordion.Trigger>{item.title}\u003C\u002FAccordion.Trigger>\n        \u003CAccordion.Content>{item.content}\u003C\u002FAccordion.Content>\n      \u003C\u002FAccordion.Item>\n    ))}\n  \u003C\u002FAccordion.Root>\n);\n```\n\n## Naming Conventions\n\nWhen building composable components, consistent naming conventions are crucial for creating intuitive and predictable APIs. Both shadcn\u002Fui and Radix UI follow established patterns that have become the de facto standard in the React ecosystem.\n\n### Root Components\n\nThe `Root` component serves as the main container that wraps all other sub-components. It typically manages shared state and context by providing a context to all child components.\n\n```tsx\n\u003CAccordionRoot>{\u002F* Child components *\u002F}\u003C\u002FAccordionRoot>\n```\n\n### Interactive Elements\n\nInteractive components that trigger actions or toggle states use descriptive names:\n\n- `Trigger` - The element that initiates an action (opening, closing, toggling)\n- `Content` - The element that contains the main content being shown\u002Fhidden\n\n```tsx\n\u003CCollapsibleTrigger>Click to expand\u003C\u002FCollapsibleTrigger>\n\u003CCollapsibleContent>\n  Hidden content revealed here\n\u003C\u002FCollapsibleContent>\n```\n\n### Content Structure\n\nFor components with structured content areas, use semantic names that describe their purpose:\n\n- `Header` - Top section containing titles or controls\n- `Body` - Main content area\n- `Footer` - Bottom section for actions or metadata\n\n```tsx\n\u003CDialogHeader>\n  {\u002F* Form title *\u002F}\n\u003C\u002FDialogHeader>\n\u003CDialogBody>\n  {\u002F* Form content *\u002F}\n\u003C\u002FDialogBody>\n\u003CDialogFooter>\n  {\u002F* Form footer *\u002F}\n\u003C\u002FDialogFooter>\n```\n\n### Informational Components\n\nComponents that provide information or context use descriptive suffixes:\n\n- `Title` - Primary heading or label\n- `Description` - Supporting text or explanatory content\n\n```tsx\n\u003CCardTitle>Project Statistics\u003C\u002FCardTitle>\n\u003CCardDescription>\n  View your project's performance over time\n\u003C\u002FCardDescription>\n```\n\n# Data Attributes\n\nURL: \u002Fdata-attributes\n\n\ntitle: Data Attributes\ndescription: Add data attributes to expose component state and enable flexible styling.\n\n\nData attributes provide a way to expose component state and structure to consumers for styling. Use two patterns: `data-state` for visual states and `data-slot` for component identification.\n\n## When Creating Components\n\n**Add `data-state` attributes** to expose component state:\n\n- Visual states (open\u002Fclosed, active\u002Finactive, loading)\n- Layout states (orientation, side, alignment)\n- Interaction states (disabled, hover, focus when styling children)\n\n**Add `data-slot` attributes** for stable component identification:\n\n- Use kebab-case naming (`data-slot=\"submit-button\"`)\n- Name reflects purpose, not implementation\n- Provides stable selectors that won't break when internals change\n\n## Decision Framework\n\nWhen creating a component, choose the appropriate API:\n\n- **`data-state`** - For states that affect styling (open\u002Fclosed, loading, disabled)\n- **`data-slot`** - For component identity (stable targeting, parent-child relationships)\n- **`props`** - For variants, sizes, behavior configuration, and event handlers\n\nA well-designed component combines all three: props for variants\u002Fbehavior, data-state for conditional styling, and data-slot for stable targeting.\n\n**For comprehensive usage patterns and examples, see the Data Attribute Styling Patterns section in react.mdc, which covers:**\n\n- Styling with `data-state` (Tailwind arbitrary variants)\n- Radix UI data attributes\n- Using `data-slot` with `has-[]` and `[&_]` selectors\n- Global CSS patterns\n- Naming conventions and best practices\n\n# Definitions\n\nURL: \u002Fdefinitions\n\n\ntitle: Definitions\ndescription: This page establishes precise terminology used throughout the specification. Terms are intentionally framework agnostic, but we will use React for examples.\n\n\n## 1. Artifact Taxonomy\n\n### 1.1 Primitive\n\nA primitive (or, unstyled component) is the **lowest‑level building block** that provides behavior and accessibility without any styling.\n\nPrimitives are completely headless (i.e. unstyled) and encapsulate semantics, focus management, keyboard interaction, layering\u002Fportals, ARIA wiring, measurement, and similar concerns. They provide the behavioral foundation but require styling to become finished UI.\n\nExamples:\n\n- [Radix UI Primitives](https:\u002F\u002Fwww.radix-ui.com\u002Fprimitives) (Dialog, Popover, Tooltip, etc.)\n- [React Aria Components](https:\u002F\u002Freact-spectrum.adobe.com\u002Freact-aria)\n- [Base UI](https:\u002F\u002Fbase-ui.com)\n- [Headless UI](https:\u002F\u002Fheadlessui.com\u002F)\n\nExpectations:\n\n- Completely unstyled (headless).\n- Single responsibility; composable into styled components.\n- Ships with exhaustive a11y behavior for its role.\n- Versioning favors stability; breaking changes are rare and documented.\n\n\u003CCallout>\n  The terms primitive and component are typically used interchangeably across the web, but they are not the same.\n\u003C\u002FCallout>\n\n### 1.2 Component\n\nA component is a styled, reusable UI unit that adds visual design to primitives or composes multiple elements to create complete, functional interface elements.\n\nComponents are still relatively low-level but include styling, making them immediately usable in applications. They typically wrap unstyled primitives with default visual design while remaining customizable.\n\nExamples:\n\n- [shadcn\u002Fui components](https:\u002F\u002Fui.shadcn.com\u002F) (styled wrappers of Radix primitives)\n- [Material UI components](https:\u002F\u002Fmui.com\u002Fcomponents\u002F)\n- [Ant Design components](https:\u002F\u002Fant.design\u002Fcomponents\u002Foverview\u002F)\n\nExpectations:\n\n- Clear props API; supports controlled and uncontrolled usage where applicable.\n- Includes default styling but remains override-friendly (classes, tokens, slots).\n- Fully keyboard accessible and screen-reader friendly (inherits from primitives).\n- Composable (children\u002Fslots, render props, or compound subcomponents).\n- May be built from primitives or implement behavior directly with styling.\n\n### 1.3 Pattern\n\nPatterns are a specific composition of primitives or components that are used to solve a specific UI\u002FUX problem.\n\nExamples:\n\n- Form validation with inline errors\n- Confirming destructive actions\n- Typeahead search\n- Optimistic UI\n\nExpectations.\n\n- Describes behavior, a11y, keyboard map, and failure modes.\n- May include reference implementations in multiple frameworks.\n\n### 1.4 Block\n\nAn opinionated, production-ready composition of components that solves a concrete interface use case (often product-specific) with content scaffolding. Blocks trade generality for speed of adoption.\n\nExamples:\n\n- Pricing table\n- Auth screens\n- Onboarding stepper\n- AI chat panel\n- Billing settings form\n\nExpectations.\n\n- Strong defaults, copy-paste friendly, easily branded\u002Fthemed.\n- Minimal logic beyond layout and orchestration; domain logic is stubbed via handlers.\n- Accepts data via props; never hides data behind fetches without a documented adapter.\n\n\u003CAuthorNote name=\"Rob Austin\" role=\"Founder of shadcnblocks.com\" githubUsername=\"JugglerX\" link=\"https:\u002F\u002Fwww.shadcnblocks.com\u002F\">\n  Blocks are typically not reusable like a component. You don't import them, but they typically import components and primitives. This makes them good candidates for a [Registry](\u002Fregistry) distribution method.\n\u003C\u002FAuthorNote>\n\n### 1.5 Page\n\nA complete, single-route view composed of multiple blocks arranged to serve a specific user-facing purpose. Pages combine blocks into a cohesive layout that represents one destination in an application.\n\nExamples:\n\n- Landing page (hero block + features block + pricing block + footer block)\n- Product detail page (image gallery block + product info block + reviews block)\n- Dashboard page (stats block + chart block + activity feed block)\n\nExpectations:\n\n- Combines multiple blocks into a unified layout for a single route.\n- Focuses on layout and block orchestration rather than component-level details.\n- May include page-specific logic for data coordination between blocks.\n- Self-contained for a single URL\u002Froute; not intended to be reused across routes.\n\n### 1.6 Template\n\nA multi-page collection or full-site scaffold that bundles pages, routing configuration, shared layouts, global providers, and project structure. Templates are complete starting points for entire applications or major application sections.\n\nExamples:\n\n- [TailwindCSS Templates](https:\u002F\u002Ftailwindui.com\u002Ftemplates)\n- [shadcnblocks Templates](https:\u002F\u002Fwww.shadcnblocks.com\u002Ftemplates) (full application shells)\n- \"SaaS starter\" (auth pages + dashboard pages + settings pages + marketing pages)\n- \"E-commerce template\" (storefront + product pages + checkout flow + admin pages)\n\nExpectations:\n\n- Includes multiple pages with routing\u002Fnavigation structure.\n- Provides global configuration (theme providers, auth context, layout shells).\n- Opinionated project structure with clear conventions.\n- Designed as a comprehensive starting point; fork and customize rather than import as dependency.\n- May include build configuration, deployment setup, and development tooling.\n\n### 1.7 Utility (Non-visual)\n\nA helper exported for developer ergonomics or composition; not rendered UI.\n\nExamples:\n\n- React hooks (useControllableState, useId)\n- Class utilities\n- Keybinding helpers\n- Focus scopes\n\nExpectations.\n\n- Side-effect free (except where explicitly documented).\n- Testable in isolation; supports tree-shaking.\n\n## 2. API and Composition Vocabulary\n\n### 2.1 Props API\n\nThe public configuration surface of a component. Props are stable, typed, and documented with defaults and a11y ramifications.\n\n### 2.2 Children \u002F Slots\n\nPlaceholders for caller-provided structure or content.\n\n- Children (implicit slot). JSX between opening\u002Fclosing tags.\n- Named slots. Props like icon, footer, or `\u003CComponent.Slot>` subcomponents.\n- Slot forwarding. Passing DOM attributes\u002FclassName\u002Frefs through to the underlying element.\n\n### 2.3 Render Prop (Function-as-Child)\n\nA function child used to delegate rendering while the parent supplies state\u002Fdata.\n\n```tsx\n\u003CParentComponent data={data}>\n  {(item) => \u003CChildComponent key={item.id} {...item} \u002F>}\n\u003C\u002FParentComponent>\n```\n\nUse when the parent must own data\u002Fbehavior but the consumer must fully control markup.\n\n### 2.4 Controlled vs. Uncontrolled\n\n**Controlled** and **uncontrolled** are terms used to describe the state of a component.\n\n**Controlled** components have their value driven by props, and typically emit an `onChange` event (source of truth is the parent). **Uncontrolled** components hold internal state; and may expose a `defaultValue` and imperative reset.\n\nMany inputs should support both. Learn more about [controlled and uncontrolled state](\u002Fstate).\n\n### 2.5 Provider \u002F Context\n\nA top-level component that supplies shared state\u002Fconfiguration to a subtree (e.g., theme, locale, active tab id). Providers are explicitly documented with required placement.\n\n### 2.6 Portal\n\nRendering UI outside the DOM hierarchy to manage layering\u002Fstacking context (e.g., modals, popovers, toasts), while preserving a11y (focus trap, aria-modal, inert background).\n\n## 3. Styling and Theming Vocabulary\n\n### 3.1 Headless\n\nImplements behavior and accessibility without prescribing appearance. Requires the consumer to supply styling.\n\n### 3.2 Styled\n\nShips with default visual design (CSS classes, inline styles, or tokens) but remains override-friendly (className merge, CSS vars, theming).\n\n### 3.3 Variants\n\nDiscrete, documented style or behavior permutations exposed via props (e.g., `size=\"sm|md|lg\"`, `tone=\"neutral|destructive\"`). Variants are not separate components.\n\n### 3.4 Design Tokens\n\nNamed, platform-agnostic values (e.g., `--color-bg`, `--radius-md`, `--space-2`) that parameterize visual design and support theming.\n\n## 4. Accessibility Vocabulary\n\n### 4.1 Role \u002F State \u002F Property\n\nWAI-ARIA attributes that communicate semantics (`role=\"menu\"`), state (`aria-checked`), and relationships (`aria-controls`, `aria-labelledby`).\n\n### 4.2 Keyboard Map\n\nThe documented set of keyboard interactions for a widget (e.g., `Tab`, `Arrow keys`, `Home\u002FEnd`, `Escape`). Every interactive component declares and implements a keyboard map.\n\n### 4.3 Focus Management\n\nRules for initial focus, roving focus, focus trapping, and focus return on teardown.\n\n## 5. Distribution Vocabulary\n\n### 5.1 Package (Registry Distribution)\n\nThe component\u002Flibrary is published to a package registry (e.g., `npm`) and imported via a bundler. Favors versioned updates and dependency management.\n\n### 5.2 Copy-and-Paste (Source Distribution)\n\nSource code is integrated directly into the consumer's repository (often via a CLI). Favors ownership, customization, and zero extraneous runtime.\n\n### 5.3 Registry (Catalog)\n\nA curated index of artifacts (primitives, components, blocks, templates) with metadata, previews, and install\u002Fcopy instructions. A registry is not necessarily a package manager.\n\n## 6. Classification Heuristics\n\nUse this decision flow to name and place an artifact:\n\n1. Does it encapsulate a single behavior or a11y concern, with no styling? → **Primitive**\n2. Is it a styled, reusable UI element that adds visual design to primitives or composes multiple elements? → **Component**\n3. Does it solve a concrete product use case with opinionated composition and copy? → **Block**\n4. Does it scaffold a page\u002Fflow with routing\u002Fproviders and replaceable regions? → **Template**\n5. Is it documentation of a recurring solution, independent of implementation? → **Pattern**\n6. Is it non-visual logic for ergonomics\u002Fcomposition? → **Utility**\n\n## 7. Non-Goals and Clarifications\n\n- Web Components vs. \"Components.\" In this spec, \"component\" refers to a reusable UI unit (examples in React). It does not imply the HTML Custom Elements standard unless explicitly stated. Equivalent principles apply across frameworks.\n- Widgets. The term “widget” is avoided due to ambiguity; use component (general) or pattern (documentation-only solution).\n- Themes vs. Styles. A theme is a parameterization of styles (via tokens). Styles are the concrete presentation. Components should support themes; blocks\u002Ftemplates may ship opinionated styles plus theming hooks.\n\n# Design Tokens\n\nURL: \u002Fdesign-tokens\n\n\ntitle: Design Tokens\ndescription: How semantic naming conventions and design tokens create a flexible, maintainable theming system.\n\n\nDesign tokens are semantic CSS variables that separate theme, context, and usage concerns. Rather than hardcoding colors, use a semantic naming convention that creates layers of abstraction between what something is and how it looks.\n\nThis architectural decision creates a maintainable, flexible system that scales across applications.\n\n**For practical implementation and examples, see the Design Tokens section in react.mdc, which covers:**\n\n- Variable architecture and structure\n- Common token patterns (`--background`, `--foreground`, `--primary`, etc.)\n- Theme switching (light\u002Fdark modes)\n- Usage in components\n\n# Overview\n\nURL: \u002F\n\n\ntitle: Overview\ndescription: components.build is an open-source standard for building modern, composable and accessible UI components.\n\n\nModern web applications are built on reusable UI components and how we design, build, and share them is important. This specification aims to establish a formal, open standard for building open-source UI components for the modern web.\n\nIt is co-authored by \u003CAuthor name=\"Hayden Bleasel\" image=\"https:\u002F\u002Fgithub.com\u002Fhaydenbleasel.png\" href=\"https:\u002F\u002Fx.com\u002Fhaydenbleasel\" \u002F> and \u003CAuthor name=\"shadcn\" image=\"https:\u002F\u002Fgithub.com\u002Fshadcn.png\" href=\"https:\u002F\u002Fx.com\u002Fshadcn\" \u002F>, with contributions from the open-source community and informed by popular projects in the React ecosystem.\n\nThe goal is to help open-source maintainers and senior front-end engineers create components that are composable, accessible, and easy to adopt across projects.\n\n## What is this specification?\n\nThis spec is not a tutorial or course on React, nor a promotion for any specific component library or registry. Instead, it provides high-level guidelines, best practices, and a common terminology for designing UI components.\n\nBy following this specification, developers can ensure their components are consistent with modern expectations and can integrate smoothly into any codebase.\n\n## Who is this for?\n\nWe're writing this for open-source maintainers and experienced front-end engineers who build and distribute component libraries or design systems. We assume you are familiar with JavaScript\u002FTypeScript and React.\n\nAll examples will use React (with JSX\u002FTSX) for concreteness, but we hope the fundamental concepts apply to other frameworks like Vue, Svelte, or Angular.\n\nIn other words, we hope this spec’s philosophy is framework-agnostic – whether you build with React or another library, you should emphasize the same principles of composition, accessibility, and maintainability.\n\n# Polymorphism\n\nURL: \u002Fpolymorphism\n\n\ntitle: Polymorphism\ndescription: How to use the `as` prop to change the rendered HTML element while preserving component functionality.\n\n\nThe `as` prop is a fundamental pattern in modern React component libraries that allows you to change the underlying HTML element or component that gets rendered.\n\nPopularized by libraries like [Styled Components](https:\u002F\u002Fstyled-components.com\u002F), [Emotion](https:\u002F\u002Femotion.sh\u002F), and [Chakra UI](https:\u002F\u002Fchakra-ui.com\u002F), this pattern provides flexibility in choosing semantic HTML while maintaining component styling and behavior.\n\nThe `as` prop enables polymorphic components - components that can render as different element types while preserving their core functionality:\n\n```tsx\n\u003CButton as=\"a\" href=\"\u002Fhome\">\n  Go Home\n\u003C\u002FButton>\n\n\u003CButton as=\"button\" type=\"submit\">\n  Submit Form\n\u003C\u002FButton>\n\n\u003CButton as=\"div\" role=\"button\" tabIndex={0}>\n  Custom Element\n\u003C\u002FButton>\n```\n\n## Understanding `as`\n\nThe `as` prop allows you to override the default element type of a component. Instead of being locked into a specific HTML element, you can adapt the component to render as any valid HTML tag or even another React component.\n\n```tsx\n\u003CBox>Content\u003C\u002FBox>              \u002F\u002F Renders as default (div)\n\u003CBox as=\"section\">Content\u003C\u002FBox>  \u002F\u002F Renders as \u003Csection>\n\u003CBox as=\"nav\">Content\u003C\u002FBox>      \u002F\u002F Renders as \u003Cnav>\n```\n\n## Implementation Methods\n\nThere are two main approaches to implementing polymorphic components: a manual implementation and using Radix UI's `Slot` component.\n\n### Manual Implementation\n\nThe `as` prop implementation uses dynamic component rendering:\n\n```tsx\n\u002F\u002F Simplified implementation\nfunction Component({ as: Element = 'div', children, ...props }) {\n  return \u003CElement {...props}>{children}\u003C\u002FElement>;\n}\n\n\u002F\u002F More complete implementation with TypeScript\ntype PolymorphicProps\u003CE extends React.ElementType> = {\n  as?: E;\n  children?: React.ReactNode;\n} & React.ComponentPropsWithoutRef\u003CE>;\n\nfunction Component\u003CE extends React.ElementType = 'div'>({\n  as,\n  children,\n  ...props\n}: PolymorphicProps\u003CE>) {\n  const Element = as || 'div';\n  return \u003CElement {...props}>{children}\u003C\u002FElement>;\n}\n```\n\nThe component:\n\n1. Accepts an `as` prop with a default element type\n2. Uses the provided element or fallback to default\n3. Spreads all other props to the rendered element\n4. Maintains type safety with TypeScript generics\n\n### Using Radix UI Slot\n\n[Radix UI](https:\u002F\u002Fwww.radix-ui.com\u002F) provides a `Slot` component that offers a more powerful alternative to the `as` prop pattern. Instead of just changing the element type, `Slot` merges props with the child component, enabling composition patterns.\n\nFirst, install the package:\n\n```package-install\nnpm install @radix-ui\u002Freact-slot\n```\n\nThe `asChild` pattern uses a boolean prop instead of specifying the element type:\n\n```tsx\nimport { Slot } from '@radix-ui\u002Freact-slot';\nimport { cva, type VariantProps } from 'class-variance-authority';\n\nconst itemVariants = cva('rounded-lg border p-4', {\n  variants: {\n    variant: {\n      default: 'bg-white',\n      primary: 'bg-blue-500 text-white',\n    },\n    size: {\n      default: 'h-10 px-4',\n      sm: 'h-8 px-3',\n      lg: 'h-12 px-6',\n    },\n  },\n  defaultVariants: {\n    variant: 'default',\n    size: 'default',\n  },\n});\n\nfunction Item({\n  className,\n  variant = 'default',\n  size = 'default',\n  asChild = false,\n  ...props\n}: React.ComponentProps\u003C'div'> & VariantProps\u003Ctypeof itemVariants> & { asChild?: boolean }) {\n  const Comp = asChild ? Slot : 'div';\n  return (\n    \u003CComp\n      data-slot=\"item\"\n      data-variant={variant}\n      data-size={size}\n      className={cn(itemVariants({ variant, size, className }))}\n      {...props}\n    \u002F>\n  );\n}\n```\n\nNow you can use it in two ways:\n\n```tsx\n\u002F\u002F Default: renders as a div\n\u003CItem variant=\"primary\">Content\u003C\u002FItem>\n\n\u002F\u002F With asChild: merges props with child component\n\u003CItem variant=\"primary\" asChild>\n  \u003Ca href=\"\u002Fhome\">Link with Item styles\u003C\u002Fa>\n\u003C\u002FItem>\n```\n\nThe `Slot` component:\n\n1. Clones the child element\n2. Merges the component's props (className, data attributes, etc.) with the child's props\n3. Forwards refs correctly\n4. Handles event handler composition\n\n### Comparison: `as` vs `asChild`\n\n**`as` prop (manual implementation):**\n\n```tsx\n\u002F\u002F Explicit element type\n\u003CButton as=\"a\" href=\"\u002Fhome\">Link Button\u003C\u002FButton>\n\u003CButton as=\"button\" type=\"submit\">Submit Button\u003C\u002FButton>\n\n\u002F\u002F Simple, predictable API\n\u002F\u002F Limited to element types\n```\n\n**`asChild` with Slot:**\n\n```tsx\n\u002F\u002F Implicit from child\n\u003CButton asChild>\n  \u003Ca href=\"\u002Fhome\">Link Button\u003C\u002Fa>\n\u003C\u002FButton>\n\n\u003CButton asChild>\n  \u003Cbutton type=\"submit\">Submit Button\u003C\u002Fbutton>\n\u003C\u002FButton>\n\n\u002F\u002F More flexible composition\n\u002F\u002F Works with any component\n\u002F\u002F Better prop merging\n```\n\n**Key differences:**\n\n| Feature                   | `as` prop           | `asChild` + Slot                 |\n| ------------------------- | ------------------- | -------------------------------- |\n| **API Style**             | `\u003CButton as=\"a\">`   | `\u003CButton asChild>\u003Ca \u002F>\u003C\u002FButton>` |\n| **Element Type**          | Specified in prop   | Inferred from child              |\n| **Component Composition** | Limited             | Full support                     |\n| **Prop Merging**          | Basic spread        | Intelligent merging              |\n| **Ref Forwarding**        | Manual setup needed | Built-in                         |\n| **Event Handlers**        | May conflict        | Composed correctly               |\n| **Library Size**          | No dependency       | Requires `@radix-ui\u002Freact-slot`  |\n\n### When to Use Each Approach\n\n**Use `as` prop when:**\n\n- You want a simpler API surface\n- You're primarily switching between HTML elements\n- You want to avoid additional dependencies\n- The component is simple and doesn't need complex prop merging\n\n**Use `asChild` + Slot when:**\n\n- You need to compose with other components\n- You want automatic prop merging behavior\n- You're building a component library similar to Radix UI or shadcn\u002Fui\n- You need reliable ref forwarding across different component types\n\n## Key Benefits\n\n1. **Semantic HTML Flexibility** - Use the most appropriate element (`\u003CContainer as=\"nav\">`, `\u003CContainer as=\"main\">`, `\u003CContainer as=\"aside\">`)\n2. **Component Reusability** - One component serves multiple purposes (`\u003CText as=\"h1\">`, `\u003CText as=\"p\">`, `\u003CText as=\"label\">`)\n3. **Accessibility** - Choose elements with best a11y for context (`\u003CButton as=\"a\" href=\"\u002F\">` vs `\u003CButton as=\"button\">`)\n4. **Style System Integration** - Maintain consistent styling while changing elements\n\n## Common Use Cases\n\n- **Typography** - Flexible text components that can render as headings, paragraphs, labels, etc.\n- **Layout** - Semantic layout components (Flex, Grid, Stack) that adapt to semantic containers\n- **Interactive** - Components that handle buttons, links, and custom interactive elements with proper accessibility\n\n## TypeScript Best Practices\n\nUse generic types for full type safety:\n\n```tsx\ntype PolymorphicProps\u003CE extends React.ElementType, Props = {}> = Props &\n  Omit\u003CReact.ComponentPropsWithoutRef\u003CE>, keyof Props> & { as?: E };\n\nfunction Component\u003CE extends React.ElementType = 'div'>({\n  as,\n  ...props\n}: PolymorphicProps\u003CE, { customProp?: string }>) {\n  const Element = as || 'div';\n  return \u003CElement {...props} \u002F>;\n}\n```\n\nThis enables automatic prop inference (`\u003CComponent as=\"a\" href=\"\u002F\">` validates href, but `\u003CComponent as=\"div\" href=\"\u002F\">` errors).\n\n## Best Practices\n\n1. **Default to semantic elements** - Choose meaningful defaults (`as: Element = 'article'` not `'div'`)\n2. **Document valid elements** - Use JSDoc and TypeScript unions to specify supported elements\n3. **Validate element appropriateness** - Warn in development when accessibility attributes are missing\n4. **Handle event handlers properly** - Add keyboard support when using non-button elements as clickable\n\n## Common Pitfalls\n\n1. **Invalid HTML nesting** - Avoid invalid combinations (button in button, div in p)\n2. **Missing accessibility** - Add ARIA labels when using semantic elements (`\u003CBox as=\"nav\" aria-label=\"...\">`)\n3. **Type safety loss** - Use generic types, not `any`\n4. **Performance** - Don't create components inline, define them outside the render function\n\n# Core Principles\n\nURL: \u002Fprinciples\n\n\ntitle: Core Principles\ndescription: When building modern UI components, it's important to keep these core principles in mind.\n\n\n## Composability and Reusability\n\nFavor composition over inheritance – build components that can be combined and nested to create more complex UIs, rather than relying on deep class hierarchies.\n\nComposable components expose a clear API (via props\u002Fslots) that allows developers to customize behavior and appearance by plugging in child elements or callbacks.\n\nThis makes components highly reusable in different contexts. (React’s design reinforces this: “Props and composition give you all the flexibility you need to customize a component’s look and behavior in an explicit and safe way.”)\n\n## Accessible by Default\n\nComponents must be usable by all users. Use semantic HTML elements appropriate to the component’s role (e.g. `\u003Cbutton>` for clickable actions, `\u003Cul>\u002F\u003Cli>` for lists, etc.) and augment with WAI-ARIA attributes when necessary.\n\nEnsure keyboard navigation and focus management are supported (for example, arrow-key navigation in menus, focus traps in modals). Each component should adhere to accessibility standards and guidelines out of the box.\n\nThis means providing proper ARIA roles\u002Fstates and testing with screen readers. Accessibility is not optional – it’s a baseline feature of every component.\n\n## Customizability and Theming\n\nA component should be easy to restyle or adapt to different design requirements. Avoid hard-coding visual styles that cannot be overridden.\n\nProvide mechanisms for theming and styling, such as CSS variables, clearly documented class names, or style props. Ideally, components come with sensible default styling but allow developers to customize appearance with minimal effort (for example, by passing a className or using design tokens).\n\nThis principle ensures components can fit into any brand or design system without “fighting” against default styles.\n\n## Lightweight and Performant\n\nComponents should be as lean as possible in terms of assets and dependencies. Avoid bloating a component with large library dependencies or overly complex logic, especially if that logic isn’t always needed.\n\nStrive for good performance (both rendering and interaction) by minimizing unnecessary re-renders and using efficient algorithms for heavy tasks. If a component is data-intensive (like a large list or table), consider patterns like virtualization or incremental rendering, but keep such features optional.\n\nLightweight components are easier to maintain and faster for end users.\n\n## Transparency and Code Ownership\n\nIn open-source, consumers often benefit from having full visibility and control of component code. This spec encourages an “open-source first” mindset: components should not be black boxes.\n\nWhen developers import or copy your component, they should be able to inspect how it works and modify it if needed. This principle underlies the emerging “copy-and-paste” distribution model (discussed later) where developers integrate component code directly into their projects.\n\nBy giving users ownership of the code, you increase trust and allow deeper customization.\n\nEven if you distribute via a package, embrace transparency by providing source maps, readable code, and thorough documentation.\n\n# State\n\nURL: \u002Fstate\n\n\ntitle: State\ndescription: How to manage state in a component, as well as merging controllable and uncontrolled state.\n\n\nBuilding flexible components that work in both controlled and uncontrolled modes is a hallmark of professional components.\n\n## Uncontrolled State\n\nUncontrolled state is when the component manages its own state internally. This is the default usage pattern for most components.\n\nFor example, here's a simple `Stepper` component that manages its own state internally:\n\n```tsx title=\"stepper.tsx\"\nimport { useState } from 'react';\n\nexport const Stepper = () => {\n  const [value, setValue] = useState(0);\n\n  return (\n    \u003Cdiv>\n      \u003Cp>{value}\u003C\u002Fp>\n      \u003Cbutton onClick={() => setValue(value + 1)}>Increment\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n};\n```\n\n## Controlled State\n\nControlled state is when the component's state is managed by the parent component. Rather than keeping track of the state internally, we delegate this responsibility to the parent component.\n\nLet's rework the `Stepper` component to be controlled by the parent component:\n\n```tsx title=\"stepper.tsx\"\ntype StepperProps = {\n  value: number;\n  setValue: (value: number) => void;\n};\n\nexport const Stepper = ({ value, setValue }: StepperProps) => (\n  \u003Cdiv>\n    \u003Cp>{value}\u003C\u002Fp>\n    \u003Cbutton onClick={() => setValue(value + 1)}>Increment\u003C\u002Fbutton>\n  \u003C\u002Fdiv>\n);\n```\n\n## Merging states\n\nThe best components support both controlled and uncontrolled state. This allows the component to be used in a variety of scenarios, and to be easily customized.\n\n[Radix UI](https:\u002F\u002Fwww.radix-ui.com\u002F) maintain an internal utility for merging controllable and uncontrolled state called [`use-controllable-state`](https:\u002F\u002Fgithub.com\u002Fradix-ui\u002Fprimitives\u002Ftree\u002Fmain\u002Fpackages\u002Freact\u002Fuse-controllable-state). While not intended for public use, registries like [Kibo UI](https:\u002F\u002Fwww.kibo-ui.com) have implemented this utility to build their own Radix-like components.\n\nLet's install the hook:\n\n```package-install\nnpm install @radix-ui\u002Freact-use-controllable-state\n```\n\nThis lightweight hook gives you the same state management patterns used internally by Radix UI's component library, ensuring your components behave consistently with industry standards.\n\nThe hook accepts three main parameters and returns a tuple with the current value and setter. Let's use it to merge the controlled and uncontrolled state of the `Stepper` component:\n\n```tsx title=\"stepper.tsx\"\nimport { useControllableState } from '@radix-ui\u002Freact-use-controllable-state';\n\ntype StepperProps = {\n  value: number;\n  defaultValue: number;\n  onValueChange: (value: number) => void;\n};\n\nexport const Stepper = ({ value: controlledValue, defaultValue, onValueChange }: StepperProps) => {\n  const [value, setValue] = useControllableState({\n    prop: controlledValue, \u002F\u002F The controlled value prop\n    defaultProp: defaultValue, \u002F\u002F Default value for uncontrolled mode\n    onChange: onValueChange, \u002F\u002F Called when value changes\n  });\n\n  return (\n    \u003Cdiv>\n      \u003Cp>{value}\u003C\u002Fp>\n      \u003Cbutton onClick={() => setValue(value + 1)}>Increment\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n};\n```\n\n# Types\n\nURL: \u002Ftypes\n\n\ntitle: Types\ndescription: Extending the browser's native HTML elements for maximum customization.\n\n\nWhen building reusable components, proper typing is essential for creating flexible, customizable, and type-safe interfaces. By following established patterns for component types, you can ensure your components are both powerful and easy to use.\n\n## Single Element Wrapping\n\nEach exported component should ideally wrap a single HTML or JSX element. This principle is fundamental to creating composable, customizable components.\n\nWhen a component wraps multiple elements, it becomes difficult to customize specific parts without prop drilling or complex APIs. Consider this anti-pattern:\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Fcard.tsx\"\nconst Card = ({ title, description, footer, ...props }) => (\n  \u003Cdiv {...props}>\n    \u003Cdiv className=\"card-header\">\n      \u003Ch2>{title}\u003C\u002Fh2>\n      \u003Cp>{description}\u003C\u002Fp>\n    \u003C\u002Fdiv>\n    \u003Cdiv className=\"card-footer\">{footer}\u003C\u002Fdiv>\n  \u003C\u002Fdiv>\n);\n```\n\nAs we discussed in [Composition](\u002Fdocs\u002Fcomposition), this approach creates several problems:\n\n- You can't customize the header styling without adding more props\n- You can't control the HTML elements used for title and description\n- You're forced into a specific DOM structure\n\nInstead, each layer should be its own component. This allows you to customize each layer independently, and to control the exact HTML elements used for the title and description.\n\nThe benefits of this approach are:\n\n- **Maximum customization** - Users can style and modify each layer independently\n- **No prop drilling** - Props go directly to the element that needs them\n- **Semantic HTML** - Users can see and control the exact DOM structure\n- **Better accessibility** - Direct control over ARIA attributes and semantic elements\n- **Simpler mental model** - One component = one element\n\n## Extending HTML Attributes\n\nEvery component should extend the native HTML attributes of the element it wraps. This ensures users have full control over the underlying HTML element.\n\n### Basic Pattern\n\n```tsx\nexport type CardRootProps = React.ComponentProps\u003C'div'> & {\n  \u002F\u002F Add your custom props here\n  variant?: 'default' | 'outlined';\n};\n\nexport const CardRoot = ({ variant = 'default', ...props }: CardRootProps) => \u003Cdiv {...props} \u002F>;\n```\n\n### Common HTML Attribute Types\n\nReact provides type definitions for all HTML elements. Use the appropriate one for your component:\n\n```tsx\n\u002F\u002F For div elements\ntype DivProps = React.ComponentProps\u003C'div'>;\n\n\u002F\u002F For button elements\ntype ButtonProps = React.ComponentProps\u003C'button'>;\n\n\u002F\u002F For input elements\ntype InputProps = React.ComponentProps\u003C'input'>;\n\n\u002F\u002F For form elements\ntype FormProps = React.ComponentProps\u003C'form'>;\n\n\u002F\u002F For anchor elements\ntype LinkProps = React.ComponentProps\u003C'a'>;\n```\n\n### Handling Different Element Types\n\nWhen a component can render as different elements, use generics or union types:\n\n```tsx\n\u002F\u002F Using discriminated unions\nexport type ButtonProps =\n  | (React.ComponentProps\u003C'button'> & { asChild?: false })\n  | (React.ComponentProps\u003C'div'> & { asChild: true });\n\n\u002F\u002F Or with a polymorphic approach\nexport type PolymorphicProps\u003CT extends React.ElementType> = {\n  as?: T;\n} & React.ComponentPropsWithoutRef\u003CT>;\n```\n\n### Extending custom components\n\nIf you're extending an existing component, you can use the `ComponentProps` type to get the props of the component.\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Fshare-button.tsx\"\nimport type { ComponentProps } from 'react';\n\nexport type ShareButtonProps = ComponentProps\u003C'button'>;\n\nexport const ShareButton = (props: ShareButtonProps) => \u003Cbutton {...props} \u002F>;\n```\n\n## Exporting Types\n\nAlways export your component prop types. This makes them accessible to consumers for various use cases.\n\nExporting types enables several important patterns:\n\n```tsx\n\u002F\u002F 1. Extracting specific prop types\nimport type { CardRootProps } from '@\u002Fcomponents\u002Fui\u002Fcard';\nconst variant = CardRootProps['variant'];\n\n\u002F\u002F 2. Extending components\nexport type ExtendedCardProps = CardRootProps & {\n  isLoading?: boolean;\n};\n\n\u002F\u002F 3. Creating wrapper components\nconst MyCard = (props: CardRootProps) => (\n  \u003CCardRoot {...props} className={cn('my-custom-class', props.className)} \u002F>\n);\n\n\u002F\u002F 4. Type-safe prop forwarding\nfunction useCardProps(): Partial\u003CCardRootProps> {\n  return {\n    variant: 'outlined',\n    className: 'custom-card',\n  };\n}\n```\n\nYour exported types should be named `\u003CComponentName>Props`. This is a convention that helps other developers understand the purpose of the type.\n\n## Best Practices\n\n### 1. Always Spread Props Last\n\nEnsure users can override any default props:\n\n```tsx\n\u002F\u002F ✅ Good - user props override defaults\n\u003Cdiv className=\"default-class\" {...props} \u002F>\n\n\u002F\u002F ❌ Bad - defaults override user props\n\u003Cdiv {...props} className=\"default-class\" \u002F>\n```\n\n### 2. Avoid Prop Name Conflicts\n\nDon't use prop names that conflict with HTML attributes unless intentionally overriding:\n\n```tsx\n\u002F\u002F ❌ Bad - conflicts with HTML title attribute\nexport type CardProps = React.ComponentProps\u003C'div'> & {\n  title: string; \u002F\u002F This conflicts with the HTML title attribute\n};\n\n\u002F\u002F ✅ Good - use a different name\nexport type CardProps = React.ComponentProps\u003C'div'> & {\n  heading: string;\n};\n```\n\n### 3. Document Custom Props\n\nAdd JSDoc comments to custom props for better developer experience:\n\n```tsx\nexport type DialogProps = React.ComponentProps\u003C'div'> & {\n  \u002F** Whether the dialog is currently open *\u002F\n  open: boolean;\n  \u002F** Callback when the dialog requests to be closed *\u002F\n  onOpenChange: (open: boolean) => void;\n  \u002F** Whether to render the dialog in a portal *\u002F\n  modal?: boolean;\n};\n```\n","# Accessibility\n\nURL: \u002Faccessibility\n\n\ntitle: Accessibility\ndescription: Building components that are usable by everyone, including users with disabilities who rely on assistive technologies.\n\n\nAccessibility (a11y) is not an optional feature—it's a fundamental requirement for modern web components. Every component must be usable by everyone, including people with visual, motor, auditory, or cognitive disabilities.\n\nThis guide is a non-exhaustive list of accessibility principles and patterns that you should follow when building components. It's not a comprehensive guide, but it should give you a sense of the types of issues you should be aware of.\n\nIf you use a linter with strong accessibility rules like [Ultracite](https:\u002F\u002Fwww.ultracite.ai), these types of issues will likely be caught automatically, but it's still important to understand the principles.\n\n## Core Principles\n\n1. **Semantic HTML First** - Use native elements (`\u003Cbutton>`, `\u003Cnav>`, `\u003Cul>`) for built-in accessibility\n2. **Keyboard Navigation** - Support Tab, Arrow keys, Home\u002FEnd, Escape, Enter\u002FSpace for all interactions\n3. **Screen Reader Support** - Use ARIA attributes (`aria-label`, `aria-current`, `aria-live`) for proper announcements\n4. **Visual Accessibility** - Ensure focus indicators, sufficient contrast (4.5:1), and responsive text sizing\n\n## ARIA Patterns\n\nARIA enhances semantic HTML for assistive technologies. Key rules:\n\n1. Use semantic HTML first, ARIA only when necessary\n2. Don't override native semantics\n3. All interactive elements need keyboard access and accessible names\n\n**Common Attributes:**\n\n- **Roles** - Define element type (`role=\"button\"`, `role=\"navigation\"`, `role=\"alert\"`)\n- **States** - Describe current state (`aria-checked`, `aria-expanded`, `aria-selected`)\n- **Properties** - Provide context (`aria-label`, `aria-describedby`, `aria-controls`, `aria-required`, `aria-invalid`)\n\n## Component Patterns\n\nComplex interactive components require specific accessibility patterns. For detailed implementations, consult [WAI-ARIA Authoring Practices](https:\u002F\u002Fwww.w3.org\u002FWAI\u002FARIA\u002Fapg\u002Fpatterns\u002F).\n\n**Modal\u002FDialog:**\n\n- `role=\"dialog\"`, `aria-modal=\"true\"`, `aria-labelledby`\n- Trap focus with Tab, close with Escape\n- Store and restore previous focus\n- Prevent body scroll when open\n\n**Dropdown Menu:**\n\n- `role=\"menu\"` on container, `role=\"menuitem\"` on items\n- `aria-haspopup=\"true\"`, `aria-expanded`, `aria-controls`\n- Arrow keys navigate, Enter\u002FSpace select, Escape closes\n\n**Tabs:**\n\n- `role=\"tablist\"` on container, `role=\"tab\"` on buttons, `role=\"tabpanel\"` on panels\n- `aria-selected`, `aria-controls`, `aria-labelledby`\n- Arrow Left\u002FRight navigate, Home\u002FEnd jump to first\u002Flast\n- Only active tab is focusable (`tabIndex={0\u002F-1}`)\n\n**Forms:**\n\n- `\u003Clabel htmlFor>` paired with input `id`\n- `aria-required`, `aria-invalid`, `aria-describedby` for validation\n- Error messages with `role=\"alert\"`\n- Group related inputs with `\u003Cfieldset>` and `\u003Clegend>`\n\n## Focus Management\n\n- **Focus Visible** - Use `:focus-visible` for keyboard-only focus indicators\n- **Focus Trapping** - Trap Tab\u002FShift+Tab within modals by cycling between first and last focusable elements\n- **Focus Restoration** - Store `document.activeElement` before opening overlays, restore on close\n\n## Live Regions\n\nAnnounce dynamic content changes to screen readers:\n\n- **Status Messages** - `aria-live=\"polite\"` (waits), `aria-live=\"assertive\"` (interrupts), `role=\"alert\"` for errors\n- **Progress** - `role=\"progressbar\"` with `aria-valuenow`, `aria-valuemin`, `aria-valuemax`, `aria-label`\n\n## Color and Contrast\n\n- **Contrast Ratios** - Normal text: 4.5:1, Large text (≥18pt\u002F14pt bold): 3:1, Non-text (icons, borders): 3:1\n- **Color Independence** - Never use color alone; combine with text, icons, or ARIA attributes\n\n## Mobile Accessibility\n\n- **Touch Targets** - Minimum 44×44px (iOS) or 48×48dp (Android)\n- **Viewport** - Allow zoom (`\u003Cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1\">`)\n\n## Common Pitfalls\n\n1. **Placeholder as Label** - Use persistent `\u003Clabel>`, not disappearing placeholders\n2. **Empty Buttons** - Icon buttons need `aria-label` or visually hidden text\n3. **Disabled Elements** - Use `aria-disabled` instead of `disabled` to keep focusability and explain why\n\n# asChild\n\nURL: \u002Fas-child\n\n\ntitle: asChild\ndescription: How to use the `asChild` prop to render a custom element within the component.\n\n\nThe `asChild` prop is a powerful pattern in modern React component libraries. Popularized by [Radix UI](https:\u002F\u002Fwww.radix-ui.com\u002Fprimitives\u002Fdocs\u002Fguides\u002Fcomposition) and adopted by [shadcn\u002Fui](https:\u002F\u002Fui.shadcn.com), this pattern allows you to replace default markup with custom elements while maintaining the component's functionality.\n\n## Understanding `asChild`\n\nWhen `asChild` is `true`, instead of rendering its default DOM element, the component merges its props, behaviors, and event handlers with its immediate child element.\n\n```tsx\n\u002F\u002F Without asChild: Creates wrapper\n\u003CDialog.Trigger>\u003Cbutton>Open\u003C\u002Fbutton>\u003C\u002FDialog.Trigger>\n\u002F\u002F Output: \u003Cbutton data-state=\"closed\">\u003Cbutton>Open\u003C\u002Fbutton>\u003C\u002Fbutton>\n\n\u002F\u002F With asChild: Merges props\n\u003CDialog.Trigger asChild>\u003Cbutton>Open\u003C\u002Fbutton>\u003C\u002FDialog.Trigger>\n\u002F\u002F Output: \u003Cbutton data-state=\"closed\">Open\u003C\u002Fbutton>\n```\n\n## How It Works\n\nUses `React.cloneElement` to clone the child and merge props (including event handlers) from both parent and child components. The enhanced child is returned with combined functionality.\n\n## Key Benefits\n\n1. **Semantic HTML** - Use the most appropriate element (links for navigation, buttons for actions)\n2. **Clean DOM Structure** - Eliminates wrapper elements and \"wrapper hell\"\n3. **Design System Integration** - Works seamlessly with existing component libraries\n4. **Component Composition** - Compose multiple behaviors onto a single element\n\n## Common Use Cases\n\n- **Custom Triggers** - Replace default triggers with custom components or links\n- **Accessible Navigation** - Maintain semantic navigation elements\n- **Form Integration** - Integrate with form libraries while preserving functionality\n\n## Best Practices\n\n1. **Maintain Accessibility** - Ensure child elements have proper semantics and ARIA attributes\n2. **Document Support** - Use JSDoc to document the `asChild` prop in your component interfaces\n3. **Test Forwarding** - Verify props are properly forwarded to child components\n4. **Handle Edge Cases** - Consider conditional rendering and dynamic children\n\n## Common Pitfalls\n\n1. **Not Spreading Props** - Child components must spread `...props` to receive merged behavior\n2. **Multiple Children** - `asChild` expects exactly one child element, not multiple\n3. **Fragment Children** - Fragments are not valid, use actual HTML elements\n\n# Composition\n\nURL: \u002Fcomposition\n\n\ntitle: Composition\ndescription: The foundation of building modern UI components.\n\n\nComposition, or composability, is the foundation of building modern UI components. It is one of the most powerful techniques for creating flexible, reusable components that can handle complex requirements without sacrificing API clarity.\n\nInstead of cramming all functionality into a single component with dozens of props, composition distributes responsibility across multiple cooperating components.\n\nFernando gave a great talk about this at React Universe Conf 2025, where he shared his approach to rebuilding Slack's Message Composer as a composable component.\n\n\u003CVideo src=\"https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=4KvbVq3Eg5w\" \u002F>\n\n## Making a component composable\n\nTo make a component composable, you need to break it down into smaller, more focused components. For example, let's take this Accordion component:\n\n```tsx title=\"accordion.tsx\"\nimport { Accordion } from '@\u002Fcomponents\u002Fui\u002Faccordion';\n\nconst data = [\n  {\n    title: 'Accordion 1',\n    content: 'Accordion 1 content',\n  },\n  {\n    title: 'Accordion 2',\n    content: 'Accordion 2 content',\n  },\n  {\n    title: 'Accordion 3',\n    content: 'Accordion 3 content',\n  },\n];\n\nreturn \u003CAccordion data={data} \u002F>;\n```\n\nWhile this Accordion component might seem simple, it's handling too many responsibilities. It's responsible for rendering the container, trigger and content; as well as handling the accordion state and data.\n\nCustomizing the styling of this component is difficult because it's tightly coupled. It likely requires global CSS overrides. Additionally, adding new functionality or tweaking the behavior requires modifying the component source code.\n\nTo solve this, we can break this down into smaller, more focused components.\n\n### 1. Root Component\n\nFirst, let's focus on the container - the component that holds everything together i.e. the trigger and content. This container doesn't need to know about the data, but it does need to keep track of the open state.\n\nHowever, we also want this state to be accessible by child components. So, let's use the Context API to create a context for the open state.\n\nFinally, to allow for modification of the `div` element, we'll extend the default HTML attributes.\n\nWe'll call this component the \"Root\" component.\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Faccordion.tsx\"\ntype AccordionProps = React.ComponentProps\u003C'div'> & {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n};\n\nconst AccordionContext = createContext\u003CAccordionProps>({\n  open: false,\n  setOpen: () => {},\n});\n\nexport type AccordionRootProps = React.ComponentProps\u003C'div'> & {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n};\n\nexport const Root = ({ children, open, setOpen, ...props }: AccordionRootProps) => (\n  \u003CAccordionContext.Provider value={{ open, setOpen }}>\n    \u003Cdiv {...props}>{children}\u003C\u002Fdiv>\n  \u003C\u002FAccordionContext.Provider>\n);\n```\n\n### 2. Item Component\n\nThe Item component is the element that contains the accordion item. It is simply a wrapper for each item in the accordion.\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Faccordion.tsx\"\nexport type AccordionItemProps = React.ComponentProps\u003C'div'>;\n\nexport const Item = (props: AccordionItemProps) => \u003Cdiv {...props} \u002F>;\n```\n\n### 3. Trigger Component\n\nThe Trigger component is the element that opens the accordion when activated. It is responsible for:\n\n- Rendering as a button by default (can be customized with `asChild`)\n- Handling click events to open the accordion\n- Managing focus when accordion closes\n- Providing proper ARIA attributes\n\nLet's add this component to our Accordion component.\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Faccordion.tsx\"\nexport type AccordionTriggerProps = React.ComponentProps\u003C'button'> & {\n  asChild?: boolean;\n};\n\nexport const Trigger = ({ asChild, ...props }: AccordionTriggerProps) => (\n  \u003CAccordionContext.Consumer>\n    {({ open, setOpen }) => \u003Cbutton onClick={() => setOpen(!open)} {...props} \u002F>}\n  \u003C\u002FAccordionContext.Consumer>\n);\n```\n\n### 4. Content Component\n\nThe Content component is the element that contains the accordion content. It is responsible for:\n\n- Rendering the content when the accordion is open\n- Providing proper ARIA attributes\n\nLet's add this component to our Accordion component.\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Faccordion.tsx\"\nexport type AccordionContentProps = React.ComponentProps\u003C'div'> & {\n  asChild?: boolean;\n};\n\nexport const Content = ({ asChild, ...props }: AccordionContentProps) => (\n  \u003CAccordionContext.Consumer>{({ open }) => \u003Cdiv {...props} \u002F>}\u003C\u002FAccordionContext.Consumer>\n);\n```\n\n### 5. Putting it all together\n\nNow that we have all the components, we can put them together in our original file.\n\n```tsx title=\"accordion.tsx\"\nimport * as Accordion from '@\u002Fcomponents\u002Fui\u002Faccordion';\n\nconst data = [\n  {\n    title: 'Accordion 1',\n    content: 'Accordion 1 content',\n  },\n  {\n    title: 'Accordion 2',\n    content: 'Accordion 2 content',\n  },\n  {\n    title: 'Accordion 3',\n    content: 'Accordion 3 content',\n  },\n];\n\nreturn (\n  \u003CAccordion.Root open={false} setOpen={() => {}}>\n    {data.map((item) => (\n      \u003CAccordion.Item key={item.title}>\n        \u003CAccordion.Trigger>{item.title}\u003C\u002FAccordion.Trigger>\n        \u003CAccordion.Content>{item.content}\u003C\u002FAccordion.Content>\n      \u003C\u002FAccordion.Item>\n    ))}\n  \u003C\u002FAccordion.Root>\n);\n```\n\n## Naming Conventions\n\nWhen building composable components, consistent naming conventions are crucial for creating intuitive and predictable APIs. Both shadcn\u002Fui and Radix UI follow established patterns that have become the de facto standard in the React ecosystem.\n\n### Root Components\n\nThe `Root` component serves as the main container that wraps all other sub-components. It typically manages shared state and context by providing a context to all child components.\n\n```tsx\n\u003CAccordionRoot>{\u002F* Child components *\u002F}\u003C\u002FAccordionRoot>\n```\n\n### Interactive Elements\n\nInteractive components that trigger actions or toggle states use descriptive names:\n\n- `Trigger` - The element that initiates an action (opening, closing, toggling)\n- `Content` - The element that contains the main content being shown\u002Fhidden\n\n```tsx\n\u003CCollapsibleTrigger>Click to expand\u003C\u002FCollapsibleTrigger>\n\u003CCollapsibleContent>\n  Hidden content revealed here\n\u003C\u002FCollapsibleContent>\n```\n\n### Content Structure\n\nFor components with structured content areas, use semantic names that describe their purpose:\n\n- `Header` - Top section containing titles or controls\n- `Body` - Main content area\n- `Footer` - Bottom section for actions or metadata\n\n```tsx\n\u003CDialogHeader>\n  {\u002F* Form title *\u002F}\n\u003C\u002FDialogHeader>\n\u003CDialogBody>\n  {\u002F* Form content *\u002F}\n\u003C\u002FDialogBody>\n\u003CDialogFooter>\n  {\u002F* Form footer *\u002F}\n\u003C\u002FDialogFooter>\n```\n\n### Informational Components\n\nComponents that provide information or context use descriptive suffixes:\n\n- `Title` - Primary heading or label\n- `Description` - Supporting text or explanatory content\n\n```tsx\n\u003CCardTitle>Project Statistics\u003C\u002FCardTitle>\n\u003CCardDescription>\n  View your project's performance over time\n\u003C\u002FCardDescription>\n```\n\n# Data Attributes\n\nURL: \u002Fdata-attributes\n\n\ntitle: Data Attributes\ndescription: Add data attributes to expose component state and enable flexible styling.\n\n\nData attributes provide a way to expose component state and structure to consumers for styling. Use two patterns: `data-state` for visual states and `data-slot` for component identification.\n\n## When Creating Components\n\n**Add `data-state` attributes** to expose component state:\n\n- Visual states (open\u002Fclosed, active\u002Finactive, loading)\n- Layout states (orientation, side, alignment)\n- Interaction states (disabled, hover, focus when styling children)\n\n**Add `data-slot` attributes** for stable component identification:\n\n- Use kebab-case naming (`data-slot=\"submit-button\"`)\n- Name reflects purpose, not implementation\n- Provides stable selectors that won't break when internals change\n\n## Decision Framework\n\nWhen creating a component, choose the appropriate API:\n\n- **`data-state`** - For states that affect styling (open\u002Fclosed, loading, disabled)\n- **`data-slot`** - For component identity (stable targeting, parent-child relationships)\n- **`props`** - For variants, sizes, behavior configuration, and event handlers\n\nA well-designed component combines all three: props for variants\u002Fbehavior, data-state for conditional styling, and data-slot for stable targeting.\n\n**For comprehensive usage patterns and examples, see the Data Attribute Styling Patterns section in react.mdc, which covers:**\n\n- Styling with `data-state` (Tailwind arbitrary variants)\n- Radix UI data attributes\n- Using `data-slot` with `has-[]` and `[&_]` selectors\n- Global CSS patterns\n- Naming conventions and best practices\n\n# Definitions\n\nURL: \u002Fdefinitions\n\n\ntitle: Definitions\ndescription: This page establishes precise terminology used throughout the specification. Terms are intentionally framework agnostic, but we will use React for examples.\n\n\n## 1. Artifact Taxonomy\n\n### 1.1 Primitive\n\nA primitive (or, unstyled component) is the **lowest‑level building block** that provides behavior and accessibility without any styling.\n\nPrimitives are completely headless (i.e. unstyled) and encapsulate semantics, focus management, keyboard interaction, layering\u002Fportals, ARIA wiring, measurement, and similar concerns. They provide the behavioral foundation but require styling to become finished UI.\n\nExamples:\n\n- [Radix UI Primitives](https:\u002F\u002Fwww.radix-ui.com\u002Fprimitives) (Dialog, Popover, Tooltip, etc.)\n- [React Aria Components](https:\u002F\u002Freact-spectrum.adobe.com\u002Freact-aria)\n- [Base UI](https:\u002F\u002Fbase-ui.com)\n- [Headless UI](https:\u002F\u002Fheadlessui.com\u002F)\n\nExpectations:\n\n- Completely unstyled (headless).\n- Single responsibility; composable into styled components.\n- Ships with exhaustive a11y behavior for its role.\n- Versioning favors stability; breaking changes are rare and documented.\n\n\u003CCallout>\n  The terms primitive and component are typically used interchangeably across the web, but they are not the same.\n\u003C\u002FCallout>\n\n### 1.2 Component\n\nA component is a styled, reusable UI unit that adds visual design to primitives or composes multiple elements to create complete, functional interface elements.\n\nComponents are still relatively low-level but include styling, making them immediately usable in applications. They typically wrap unstyled primitives with default visual design while remaining customizable.\n\nExamples:\n\n- [shadcn\u002Fui components](https:\u002F\u002Fui.shadcn.com\u002F) (styled wrappers of Radix primitives)\n- [Material UI components](https:\u002F\u002Fmui.com\u002Fcomponents\u002F)\n- [Ant Design components](https:\u002F\u002Fant.design\u002Fcomponents\u002Foverview\u002F)\n\nExpectations:\n\n- Clear props API; supports controlled and uncontrolled usage where applicable.\n- Includes default styling but remains override-friendly (classes, tokens, slots).\n- Fully keyboard accessible and screen-reader friendly (inherits from primitives).\n- Composable (children\u002Fslots, render props, or compound subcomponents).\n- May be built from primitives or implement behavior directly with styling.\n\n### 1.3 Pattern\n\nPatterns are a specific composition of primitives or components that are used to solve a specific UI\u002FUX problem.\n\nExamples:\n\n- Form validation with inline errors\n- Confirming destructive actions\n- Typeahead search\n- Optimistic UI\n\nExpectations.\n\n- Describes behavior, a11y, keyboard map, and failure modes.\n- May include reference implementations in multiple frameworks.\n\n### 1.4 Block\n\nAn opinionated, production-ready composition of components that solves a concrete interface use case (often product-specific) with content scaffolding. Blocks trade generality for speed of adoption.\n\nExamples:\n\n- Pricing table\n- Auth screens\n- Onboarding stepper\n- AI chat panel\n- Billing settings form\n\nExpectations.\n\n- Strong defaults, copy-paste friendly, easily branded\u002Fthemed.\n- Minimal logic beyond layout and orchestration; domain logic is stubbed via handlers.\n- Accepts data via props; never hides data behind fetches without a documented adapter.\n\n\u003CAuthorNote name=\"Rob Austin\" role=\"Founder of shadcnblocks.com\" githubUsername=\"JugglerX\" link=\"https:\u002F\u002Fwww.shadcnblocks.com\u002F\">\n  Blocks are typically not reusable like a component. You don't import them, but they typically import components and primitives. This makes them good candidates for a [Registry](\u002Fregistry) distribution method.\n\u003C\u002FAuthorNote>\n\n### 1.5 Page\n\nA complete, single-route view composed of multiple blocks arranged to serve a specific user-facing purpose. Pages combine blocks into a cohesive layout that represents one destination in an application.\n\nExamples:\n\n- Landing page (hero block + features block + pricing block + footer block)\n- Product detail page (image gallery block + product info block + reviews block)\n- Dashboard page (stats block + chart block + activity feed block)\n\nExpectations:\n\n- Combines multiple blocks into a unified layout for a single route.\n- Focuses on layout and block orchestration rather than component-level details.\n- May include page-specific logic for data coordination between blocks.\n- Self-contained for a single URL\u002Froute; not intended to be reused across routes.\n\n### 1.6 Template\n\nA multi-page collection or full-site scaffold that bundles pages, routing configuration, shared layouts, global providers, and project structure. Templates are complete starting points for entire applications or major application sections.\n\nExamples:\n\n- [TailwindCSS Templates](https:\u002F\u002Ftailwindui.com\u002Ftemplates)\n- [shadcnblocks Templates](https:\u002F\u002Fwww.shadcnblocks.com\u002Ftemplates) (full application shells)\n- \"SaaS starter\" (auth pages + dashboard pages + settings pages + marketing pages)\n- \"E-commerce template\" (storefront + product pages + checkout flow + admin pages)\n\nExpectations:\n\n- Includes multiple pages with routing\u002Fnavigation structure.\n- Provides global configuration (theme providers, auth context, layout shells).\n- Opinionated project structure with clear conventions.\n- Designed as a comprehensive starting point; fork and customize rather than import as dependency.\n- May include build configuration, deployment setup, and development tooling.\n\n### 1.7 Utility (Non-visual)\n\nA helper exported for developer ergonomics or composition; not rendered UI.\n\nExamples:\n\n- React hooks (useControllableState, useId)\n- Class utilities\n- Keybinding helpers\n- Focus scopes\n\nExpectations.\n\n- Side-effect free (except where explicitly documented).\n- Testable in isolation; supports tree-shaking.\n\n## 2. API and Composition Vocabulary\n\n### 2.1 Props API\n\nThe public configuration surface of a component. Props are stable, typed, and documented with defaults and a11y ramifications.\n\n### 2.2 Children \u002F Slots\n\nPlaceholders for caller-provided structure or content.\n\n- Children (implicit slot). JSX between opening\u002Fclosing tags.\n- Named slots. Props like icon, footer, or `\u003CComponent.Slot>` subcomponents.\n- Slot forwarding. Passing DOM attributes\u002FclassName\u002Frefs through to the underlying element.\n\n### 2.3 Render Prop (Function-as-Child)\n\nA function child used to delegate rendering while the parent supplies state\u002Fdata.\n\n```tsx\n\u003CParentComponent data={data}>\n  {(item) => \u003CChildComponent key={item.id} {...item} \u002F>}\n\u003C\u002FParentComponent>\n```\n\nUse when the parent must own data\u002Fbehavior but the consumer must fully control markup.\n\n### 2.4 Controlled vs. Uncontrolled\n\n**Controlled** and **uncontrolled** are terms used to describe the state of a component.\n\n**Controlled** components have their value driven by props, and typically emit an `onChange` event (source of truth is the parent). **Uncontrolled** components hold internal state; and may expose a `defaultValue` and imperative reset.\n\nMany inputs should support both. Learn more about [controlled and uncontrolled state](\u002Fstate).\n\n### 2.5 Provider \u002F Context\n\nA top-level component that supplies shared state\u002Fconfiguration to a subtree (e.g., theme, locale, active tab id). Providers are explicitly documented with required placement.\n\n### 2.6 Portal\n\nRendering UI outside the DOM hierarchy to manage layering\u002Fstacking context (e.g., modals, popovers, toasts), while preserving a11y (focus trap, aria-modal, inert background).\n\n## 3. Styling and Theming Vocabulary\n\n### 3.1 Headless\n\nImplements behavior and accessibility without prescribing appearance. Requires the consumer to supply styling.\n\n### 3.2 Styled\n\nShips with default visual design (CSS classes, inline styles, or tokens) but remains override-friendly (className merge, CSS vars, theming).\n\n### 3.3 Variants\n\nDiscrete, documented style or behavior permutations exposed via props (e.g., `size=\"sm|md|lg\"`, `tone=\"neutral|destructive\"`). Variants are not separate components.\n\n### 3.4 Design Tokens\n\nNamed, platform-agnostic values (e.g., `--color-bg`, `--radius-md`, `--space-2`) that parameterize visual design and support theming.\n\n## 4. Accessibility Vocabulary\n\n### 4.1 Role \u002F State \u002F Property\n\nWAI-ARIA attributes that communicate semantics (`role=\"menu\"`), state (`aria-checked`), and relationships (`aria-controls`, `aria-labelledby`).\n\n### 4.2 Keyboard Map\n\nThe documented set of keyboard interactions for a widget (e.g., `Tab`, `Arrow keys`, `Home\u002FEnd`, `Escape`). Every interactive component declares and implements a keyboard map.\n\n### 4.3 Focus Management\n\nRules for initial focus, roving focus, focus trapping, and focus return on teardown.\n\n## 5. Distribution Vocabulary\n\n### 5.1 Package (Registry Distribution)\n\nThe component\u002Flibrary is published to a package registry (e.g., `npm`) and imported via a bundler. Favors versioned updates and dependency management.\n\n### 5.2 Copy-and-Paste (Source Distribution)\n\nSource code is integrated directly into the consumer's repository (often via a CLI). Favors ownership, customization, and zero extraneous runtime.\n\n### 5.3 Registry (Catalog)\n\nA curated index of artifacts (primitives, components, blocks, templates) with metadata, previews, and install\u002Fcopy instructions. A registry is not necessarily a package manager.\n\n## 6. Classification Heuristics\n\nUse this decision flow to name and place an artifact:\n\n1. Does it encapsulate a single behavior or a11y concern, with no styling? → **Primitive**\n2. Is it a styled, reusable UI element that adds visual design to primitives or composes multiple elements? → **Component**\n3. Does it solve a concrete product use case with opinionated composition and copy? → **Block**\n4. Does it scaffold a page\u002Fflow with routing\u002Fproviders and replaceable regions? → **Template**\n5. Is it documentation of a recurring solution, independent of implementation? → **Pattern**\n6. Is it non-visual logic for ergonomics\u002Fcomposition? → **Utility**\n\n## 7. Non-Goals and Clarifications\n\n- Web Components vs. \"Components.\" In this spec, \"component\" refers to a reusable UI unit (examples in React). It does not imply the HTML Custom Elements standard unless explicitly stated. Equivalent principles apply across frameworks.\n- Widgets. The term “widget” is avoided due to ambiguity; use component (general) or pattern (documentation-only solution).\n- Themes vs. Styles. A theme is a parameterization of styles (via tokens). Styles are the concrete presentation. Components should support themes; blocks\u002Ftemplates may ship opinionated styles plus theming hooks.\n\n# Design Tokens\n\nURL: \u002Fdesign-tokens\n\n\ntitle: Design Tokens\ndescription: How semantic naming conventions and design tokens create a flexible, maintainable theming system.\n\n\nDesign tokens are semantic CSS variables that separate theme, context, and usage concerns. Rather than hardcoding colors, use a semantic naming convention that creates layers of abstraction between what something is and how it looks.\n\nThis architectural decision creates a maintainable, flexible system that scales across applications.\n\n**For practical implementation and examples, see the Design Tokens section in react.mdc, which covers:**\n\n- Variable architecture and structure\n- Common token patterns (`--background`, `--foreground`, `--primary`, etc.)\n- Theme switching (light\u002Fdark modes)\n- Usage in components\n\n# Overview\n\nURL: \u002F\n\n\ntitle: Overview\ndescription: components.build is an open-source standard for building modern, composable and accessible UI components.\n\n\nModern web applications are built on reusable UI components and how we design, build, and share them is important. This specification aims to establish a formal, open standard for building open-source UI components for the modern web.\n\nIt is co-authored by \u003CAuthor name=\"Hayden Bleasel\" image=\"https:\u002F\u002Fgithub.com\u002Fhaydenbleasel.png\" href=\"https:\u002F\u002Fx.com\u002Fhaydenbleasel\" \u002F> and \u003CAuthor name=\"shadcn\" image=\"https:\u002F\u002Fgithub.com\u002Fshadcn.png\" href=\"https:\u002F\u002Fx.com\u002Fshadcn\" \u002F>, with contributions from the open-source community and informed by popular projects in the React ecosystem.\n\nThe goal is to help open-source maintainers and senior front-end engineers create components that are composable, accessible, and easy to adopt across projects.\n\n## What is this specification?\n\nThis spec is not a tutorial or course on React, nor a promotion for any specific component library or registry. Instead, it provides high-level guidelines, best practices, and a common terminology for designing UI components.\n\nBy following this specification, developers can ensure their components are consistent with modern expectations and can integrate smoothly into any codebase.\n\n## Who is this for?\n\nWe're writing this for open-source maintainers and experienced front-end engineers who build and distribute component libraries or design systems. We assume you are familiar with JavaScript\u002FTypeScript and React.\n\nAll examples will use React (with JSX\u002FTSX) for concreteness, but we hope the fundamental concepts apply to other frameworks like Vue, Svelte, or Angular.\n\nIn other words, we hope this spec’s philosophy is framework-agnostic – whether you build with React or another library, you should emphasize the same principles of composition, accessibility, and maintainability.\n\n# Polymorphism\n\nURL: \u002Fpolymorphism\n\n\ntitle: Polymorphism\ndescription: How to use the `as` prop to change the rendered HTML element while preserving component functionality.\n\n\nThe `as` prop is a fundamental pattern in modern React component libraries that allows you to change the underlying HTML element or component that gets rendered.\n\nPopularized by libraries like [Styled Components](https:\u002F\u002Fstyled-components.com\u002F), [Emotion](https:\u002F\u002Femotion.sh\u002F), and [Chakra UI](https:\u002F\u002Fchakra-ui.com\u002F), this pattern provides flexibility in choosing semantic HTML while maintaining component styling and behavior.\n\nThe `as` prop enables polymorphic components - components that can render as different element types while preserving their core functionality:\n\n```tsx\n\u003CButton as=\"a\" href=\"\u002Fhome\">\n  Go Home\n\u003C\u002FButton>\n\n\u003CButton as=\"button\" type=\"submit\">\n  Submit Form\n\u003C\u002FButton>\n\n\u003CButton as=\"div\" role=\"button\" tabIndex={0}>\n  Custom Element\n\u003C\u002FButton>\n```\n\n## Understanding `as`\n\nThe `as` prop allows you to override the default element type of a component. Instead of being locked into a specific HTML element, you can adapt the component to render as any valid HTML tag or even another React component.\n\n```tsx\n\u003CBox>Content\u003C\u002FBox>              \u002F\u002F Renders as default (div)\n\u003CBox as=\"section\">Content\u003C\u002FBox>  \u002F\u002F Renders as \u003Csection>\n\u003CBox as=\"nav\">Content\u003C\u002FBox>      \u002F\u002F Renders as \u003Cnav>\n```\n\n## Implementation Methods\n\nThere are two main approaches to implementing polymorphic components: a manual implementation and using Radix UI's `Slot` component.\n\n### Manual Implementation\n\nThe `as` prop implementation uses dynamic component rendering:\n\n```tsx\n\u002F\u002F Simplified implementation\nfunction Component({ as: Element = 'div', children, ...props }) {\n  return \u003CElement {...props}>{children}\u003C\u002FElement>;\n}\n\n\u002F\u002F More complete implementation with TypeScript\ntype PolymorphicProps\u003CE extends React.ElementType> = {\n  as?: E;\n  children?: React.ReactNode;\n} & React.ComponentPropsWithoutRef\u003CE>;\n\nfunction Component\u003CE extends React.ElementType = 'div'>({\n  as,\n  children,\n  ...props\n}: PolymorphicProps\u003CE>) {\n  const Element = as || 'div';\n  return \u003CElement {...props}>{children}\u003C\u002FElement>;\n}\n```\n\nThe component:\n\n1. Accepts an `as` prop with a default element type\n2. Uses the provided element or fallback to default\n3. Spreads all other props to the rendered element\n4. Maintains type safety with TypeScript generics\n\n### Using Radix UI Slot\n\n[Radix UI](https:\u002F\u002Fwww.radix-ui.com\u002F) provides a `Slot` component that offers a more powerful alternative to the `as` prop pattern. Instead of just changing the element type, `Slot` merges props with the child component, enabling composition patterns.\n\nFirst, install the package:\n\n```package-install\nnpm install @radix-ui\u002Freact-slot\n```\n\nThe `asChild` pattern uses a boolean prop instead of specifying the element type:\n\n```tsx\nimport { Slot } from '@radix-ui\u002Freact-slot';\nimport { cva, type VariantProps } from 'class-variance-authority';\n\nconst itemVariants = cva('rounded-lg border p-4', {\n  variants: {\n    variant: {\n      default: 'bg-white',\n      primary: 'bg-blue-500 text-white',\n    },\n    size: {\n      default: 'h-10 px-4',\n      sm: 'h-8 px-3',\n      lg: 'h-12 px-6',\n    },\n  },\n  defaultVariants: {\n    variant: 'default',\n    size: 'default',\n  },\n});\n\nfunction Item({\n  className,\n  variant = 'default',\n  size = 'default',\n  asChild = false,\n  ...props\n}: React.ComponentProps\u003C'div'> & VariantProps\u003Ctypeof itemVariants> & { asChild?: boolean }) {\n  const Comp = asChild ? Slot : 'div';\n  return (\n    \u003CComp\n      data-slot=\"item\"\n      data-variant={variant}\n      data-size={size}\n      className={cn(itemVariants({ variant, size, className }))}\n      {...props}\n    \u002F>\n  );\n}\n```\n\nNow you can use it in two ways:\n\n```tsx\n\u002F\u002F Default: renders as a div\n\u003CItem variant=\"primary\">Content\u003C\u002FItem>\n\n\u002F\u002F With asChild: merges props with child component\n\u003CItem variant=\"primary\" asChild>\n  \u003Ca href=\"\u002Fhome\">Link with Item styles\u003C\u002Fa>\n\u003C\u002FItem>\n```\n\nThe `Slot` component:\n\n1. Clones the child element\n2. Merges the component's props (className, data attributes, etc.) with the child's props\n3. Forwards refs correctly\n4. Handles event handler composition\n\n### Comparison: `as` vs `asChild`\n\n**`as` prop (manual implementation):**\n\n```tsx\n\u002F\u002F Explicit element type\n\u003CButton as=\"a\" href=\"\u002Fhome\">Link Button\u003C\u002FButton>\n\u003CButton as=\"button\" type=\"submit\">Submit Button\u003C\u002FButton>\n\n\u002F\u002F Simple, predictable API\n\u002F\u002F Limited to element types\n```\n\n**`asChild` with Slot:**\n\n```tsx\n\u002F\u002F Implicit from child\n\u003CButton asChild>\n  \u003Ca href=\"\u002Fhome\">Link Button\u003C\u002Fa>\n\u003C\u002FButton>\n\n\u003CButton asChild>\n  \u003Cbutton type=\"submit\">Submit Button\u003C\u002Fbutton>\n\u003C\u002FButton>\n\n\u002F\u002F More flexible composition\n\u002F\u002F Works with any component\n\u002F\u002F Better prop merging\n```\n\n**Key differences:**\n\n| Feature                   | `as` prop           | `asChild` + Slot                 |\n| ------------------------- | ------------------- | -------------------------------- |\n| **API Style**             | `\u003CButton as=\"a\">`   | `\u003CButton asChild>\u003Ca \u002F>\u003C\u002FButton>` |\n| **Element Type**          | Specified in prop   | Inferred from child              |\n| **Component Composition** | Limited             | Full support                     |\n| **Prop Merging**          | Basic spread        | Intelligent merging              |\n| **Ref Forwarding**        | Manual setup needed | Built-in                         |\n| **Event Handlers**        | May conflict        | Composed correctly               |\n| **Library Size**          | No dependency       | Requires `@radix-ui\u002Freact-slot`  |\n\n### When to Use Each Approach\n\n**Use `as` prop when:**\n\n- You want a simpler API surface\n- You're primarily switching between HTML elements\n- You want to avoid additional dependencies\n- The component is simple and doesn't need complex prop merging\n\n**Use `asChild` + Slot when:**\n\n- You need to compose with other components\n- You want automatic prop merging behavior\n- You're building a component library similar to Radix UI or shadcn\u002Fui\n- You need reliable ref forwarding across different component types\n\n## Key Benefits\n\n1. **Semantic HTML Flexibility** - Use the most appropriate element (`\u003CContainer as=\"nav\">`, `\u003CContainer as=\"main\">`, `\u003CContainer as=\"aside\">`)\n2. **Component Reusability** - One component serves multiple purposes (`\u003CText as=\"h1\">`, `\u003CText as=\"p\">`, `\u003CText as=\"label\">`)\n3. **Accessibility** - Choose elements with best a11y for context (`\u003CButton as=\"a\" href=\"\u002F\">` vs `\u003CButton as=\"button\">`)\n4. **Style System Integration** - Maintain consistent styling while changing elements\n\n## Common Use Cases\n\n- **Typography** - Flexible text components that can render as headings, paragraphs, labels, etc.\n- **Layout** - Semantic layout components (Flex, Grid, Stack) that adapt to semantic containers\n- **Interactive** - Components that handle buttons, links, and custom interactive elements with proper accessibility\n\n## TypeScript Best Practices\n\nUse generic types for full type safety:\n\n```tsx\ntype PolymorphicProps\u003CE extends React.ElementType, Props = {}> = Props &\n  Omit\u003CReact.ComponentPropsWithoutRef\u003CE>, keyof Props> & { as?: E };\n\nfunction Component\u003CE extends React.ElementType = 'div'>({\n  as,\n  ...props\n}: PolymorphicProps\u003CE, { customProp?: string }>) {\n  const Element = as || 'div';\n  return \u003CElement {...props} \u002F>;\n}\n```\n\nThis enables automatic prop inference (`\u003CComponent as=\"a\" href=\"\u002F\">` validates href, but `\u003CComponent as=\"div\" href=\"\u002F\">` errors).\n\n## Best Practices\n\n1. **Default to semantic elements** - Choose meaningful defaults (`as: Element = 'article'` not `'div'`)\n2. **Document valid elements** - Use JSDoc and TypeScript unions to specify supported elements\n3. **Validate element appropriateness** - Warn in development when accessibility attributes are missing\n4. **Handle event handlers properly** - Add keyboard support when using non-button elements as clickable\n\n## Common Pitfalls\n\n1. **Invalid HTML nesting** - Avoid invalid combinations (button in button, div in p)\n2. **Missing accessibility** - Add ARIA labels when using semantic elements (`\u003CBox as=\"nav\" aria-label=\"...\">`)\n3. **Type safety loss** - Use generic types, not `any`\n4. **Performance** - Don't create components inline, define them outside the render function\n\n# Core Principles\n\nURL: \u002Fprinciples\n\n\ntitle: Core Principles\ndescription: When building modern UI components, it's important to keep these core principles in mind.\n\n\n## Composability and Reusability\n\nFavor composition over inheritance – build components that can be combined and nested to create more complex UIs, rather than relying on deep class hierarchies.\n\nComposable components expose a clear API (via props\u002Fslots) that allows developers to customize behavior and appearance by plugging in child elements or callbacks.\n\nThis makes components highly reusable in different contexts. (React’s design reinforces this: “Props and composition give you all the flexibility you need to customize a component’s look and behavior in an explicit and safe way.”)\n\n## Accessible by Default\n\nComponents must be usable by all users. Use semantic HTML elements appropriate to the component’s role (e.g. `\u003Cbutton>` for clickable actions, `\u003Cul>\u002F\u003Cli>` for lists, etc.) and augment with WAI-ARIA attributes when necessary.\n\nEnsure keyboard navigation and focus management are supported (for example, arrow-key navigation in menus, focus traps in modals). Each component should adhere to accessibility standards and guidelines out of the box.\n\nThis means providing proper ARIA roles\u002Fstates and testing with screen readers. Accessibility is not optional – it’s a baseline feature of every component.\n\n## Customizability and Theming\n\nA component should be easy to restyle or adapt to different design requirements. Avoid hard-coding visual styles that cannot be overridden.\n\nProvide mechanisms for theming and styling, such as CSS variables, clearly documented class names, or style props. Ideally, components come with sensible default styling but allow developers to customize appearance with minimal effort (for example, by passing a className or using design tokens).\n\nThis principle ensures components can fit into any brand or design system without “fighting” against default styles.\n\n## Lightweight and Performant\n\nComponents should be as lean as possible in terms of assets and dependencies. Avoid bloating a component with large library dependencies or overly complex logic, especially if that logic isn’t always needed.\n\nStrive for good performance (both rendering and interaction) by minimizing unnecessary re-renders and using efficient algorithms for heavy tasks. If a component is data-intensive (like a large list or table), consider patterns like virtualization or incremental rendering, but keep such features optional.\n\nLightweight components are easier to maintain and faster for end users.\n\n## Transparency and Code Ownership\n\nIn open-source, consumers often benefit from having full visibility and control of component code. This spec encourages an “open-source first” mindset: components should not be black boxes.\n\nWhen developers import or copy your component, they should be able to inspect how it works and modify it if needed. This principle underlies the emerging “copy-and-paste” distribution model (discussed later) where developers integrate component code directly into their projects.\n\nBy giving users ownership of the code, you increase trust and allow deeper customization.\n\nEven if you distribute via a package, embrace transparency by providing source maps, readable code, and thorough documentation.\n\n# State\n\nURL: \u002Fstate\n\n\ntitle: State\ndescription: How to manage state in a component, as well as merging controllable and uncontrolled state.\n\n\nBuilding flexible components that work in both controlled and uncontrolled modes is a hallmark of professional components.\n\n## Uncontrolled State\n\nUncontrolled state is when the component manages its own state internally. This is the default usage pattern for most components.\n\nFor example, here's a simple `Stepper` component that manages its own state internally:\n\n```tsx title=\"stepper.tsx\"\nimport { useState } from 'react';\n\nexport const Stepper = () => {\n  const [value, setValue] = useState(0);\n\n  return (\n    \u003Cdiv>\n      \u003Cp>{value}\u003C\u002Fp>\n      \u003Cbutton onClick={() => setValue(value + 1)}>Increment\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n};\n```\n\n## Controlled State\n\nControlled state is when the component's state is managed by the parent component. Rather than keeping track of the state internally, we delegate this responsibility to the parent component.\n\nLet's rework the `Stepper` component to be controlled by the parent component:\n\n```tsx title=\"stepper.tsx\"\ntype StepperProps = {\n  value: number;\n  setValue: (value: number) => void;\n};\n\nexport const Stepper = ({ value, setValue }: StepperProps) => (\n  \u003Cdiv>\n    \u003Cp>{value}\u003C\u002Fp>\n    \u003Cbutton onClick={() => setValue(value + 1)}>Increment\u003C\u002Fbutton>\n  \u003C\u002Fdiv>\n);\n```\n\n## Merging states\n\nThe best components support both controlled and uncontrolled state. This allows the component to be used in a variety of scenarios, and to be easily customized.\n\n[Radix UI](https:\u002F\u002Fwww.radix-ui.com\u002F) maintain an internal utility for merging controllable and uncontrolled state called [`use-controllable-state`](https:\u002F\u002Fgithub.com\u002Fradix-ui\u002Fprimitives\u002Ftree\u002Fmain\u002Fpackages\u002Freact\u002Fuse-controllable-state). While not intended for public use, registries like [Kibo UI](https:\u002F\u002Fwww.kibo-ui.com) have implemented this utility to build their own Radix-like components.\n\nLet's install the hook:\n\n```package-install\nnpm install @radix-ui\u002Freact-use-controllable-state\n```\n\nThis lightweight hook gives you the same state management patterns used internally by Radix UI's component library, ensuring your components behave consistently with industry standards.\n\nThe hook accepts three main parameters and returns a tuple with the current value and setter. Let's use it to merge the controlled and uncontrolled state of the `Stepper` component:\n\n```tsx title=\"stepper.tsx\"\nimport { useControllableState } from '@radix-ui\u002Freact-use-controllable-state';\n\ntype StepperProps = {\n  value: number;\n  defaultValue: number;\n  onValueChange: (value: number) => void;\n};\n\nexport const Stepper = ({ value: controlledValue, defaultValue, onValueChange }: StepperProps) => {\n  const [value, setValue] = useControllableState({\n    prop: controlledValue, \u002F\u002F The controlled value prop\n    defaultProp: defaultValue, \u002F\u002F Default value for uncontrolled mode\n    onChange: onValueChange, \u002F\u002F Called when value changes\n  });\n\n  return (\n    \u003Cdiv>\n      \u003Cp>{value}\u003C\u002Fp>\n      \u003Cbutton onClick={() => setValue(value + 1)}>Increment\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n};\n```\n\n# Types\n\nURL: \u002Ftypes\n\n\ntitle: Types\ndescription: Extending the browser's native HTML elements for maximum customization.\n\n\nWhen building reusable components, proper typing is essential for creating flexible, customizable, and type-safe interfaces. By following established patterns for component types, you can ensure your components are both powerful and easy to use.\n\n## Single Element Wrapping\n\nEach exported component should ideally wrap a single HTML or JSX element. This principle is fundamental to creating composable, customizable components.\n\nWhen a component wraps multiple elements, it becomes difficult to customize specific parts without prop drilling or complex APIs. Consider this anti-pattern:\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Fcard.tsx\"\nconst Card = ({ title, description, footer, ...props }) => (\n  \u003Cdiv {...props}>\n    \u003Cdiv className=\"card-header\">\n      \u003Ch2>{title}\u003C\u002Fh2>\n      \u003Cp>{description}\u003C\u002Fp>\n    \u003C\u002Fdiv>\n    \u003Cdiv className=\"card-footer\">{footer}\u003C\u002Fdiv>\n  \u003C\u002Fdiv>\n);\n```\n\nAs we discussed in [Composition](\u002Fdocs\u002Fcomposition), this approach creates several problems:\n\n- You can't customize the header styling without adding more props\n- You can't control the HTML elements used for title and description\n- You're forced into a specific DOM structure\n\nInstead, each layer should be its own component. This allows you to customize each layer independently, and to control the exact HTML elements used for the title and description.\n\nThe benefits of this approach are:\n\n- **Maximum customization** - Users can style and modify each layer independently\n- **No prop drilling** - Props go directly to the element that needs them\n- **Semantic HTML** - Users can see and control the exact DOM structure\n- **Better accessibility** - Direct control over ARIA attributes and semantic elements\n- **Simpler mental model** - One component = one element\n\n## Extending HTML Attributes\n\nEvery component should extend the native HTML attributes of the element it wraps. This ensures users have full control over the underlying HTML element.\n\n### Basic Pattern\n\n```tsx\nexport type CardRootProps = React.ComponentProps\u003C'div'> & {\n  \u002F\u002F Add your custom props here\n  variant?: 'default' | 'outlined';\n};\n\nexport const CardRoot = ({ variant = 'default', ...props }: CardRootProps) => \u003Cdiv {...props} \u002F>;\n```\n\n### Common HTML Attribute Types\n\nReact provides type definitions for all HTML elements. Use the appropriate one for your component:\n\n```tsx\n\u002F\u002F For div elements\ntype DivProps = React.ComponentProps\u003C'div'>;\n\n\u002F\u002F For button elements\ntype ButtonProps = React.ComponentProps\u003C'button'>;\n\n\u002F\u002F For input elements\ntype InputProps = React.ComponentProps\u003C'input'>;\n\n\u002F\u002F For form elements\ntype FormProps = React.ComponentProps\u003C'form'>;\n\n\u002F\u002F For anchor elements\ntype LinkProps = React.ComponentProps\u003C'a'>;\n```\n\n### Handling Different Element Types\n\nWhen a component can render as different elements, use generics or union types:\n\n```tsx\n\u002F\u002F Using discriminated unions\nexport type ButtonProps =\n  | (React.ComponentProps\u003C'button'> & { asChild?: false })\n  | (React.ComponentProps\u003C'div'> & { asChild: true });\n\n\u002F\u002F Or with a polymorphic approach\nexport type PolymorphicProps\u003CT extends React.ElementType> = {\n  as?: T;\n} & React.ComponentPropsWithoutRef\u003CT>;\n```\n\n### Extending custom components\n\nIf you're extending an existing component, you can use the `ComponentProps` type to get the props of the component.\n\n```tsx title=\"@\u002Fcomponents\u002Fui\u002Fshare-button.tsx\"\nimport type { ComponentProps } from 'react';\n\nexport type ShareButtonProps = ComponentProps\u003C'button'>;\n\nexport const ShareButton = (props: ShareButtonProps) => \u003Cbutton {...props} \u002F>;\n```\n\n## Exporting Types\n\nAlways export your component prop types. This makes them accessible to consumers for various use cases.\n\nExporting types enables several important patterns:\n\n```tsx\n\u002F\u002F 1. Extracting specific prop types\nimport type { CardRootProps } from '@\u002Fcomponents\u002Fui\u002Fcard';\nconst variant = CardRootProps['variant'];\n\n\u002F\u002F 2. Extending components\nexport type ExtendedCardProps = CardRootProps & {\n  isLoading?: boolean;\n};\n\n\u002F\u002F 3. Creating wrapper components\nconst MyCard = (props: CardRootProps) => (\n  \u003CCardRoot {...props} className={cn('my-custom-class', props.className)} \u002F>\n);\n\n\u002F\u002F 4. Type-safe prop forwarding\nfunction useCardProps(): Partial\u003CCardRootProps> {\n  return {\n    variant: 'outlined',\n    className: 'custom-card',\n  };\n}\n```\n\nYour exported types should be named `\u003CComponentName>Props`. This is a convention that helps other developers understand the purpose of the type.\n\n## Best Practices\n\n### 1. Always Spread Props Last\n\nEnsure users can override any default props:\n\n```tsx\n\u002F\u002F ✅ Good - user props override defaults\n\u003Cdiv className=\"default-class\" {...props} \u002F>\n\n\u002F\u002F ❌ Bad - defaults override user props\n\u003Cdiv {...props} className=\"default-class\" \u002F>\n```\n\n### 2. Avoid Prop Name Conflicts\n\nDon't use prop names that conflict with HTML attributes unless intentionally overriding:\n\n```tsx\n\u002F\u002F ❌ Bad - conflicts with HTML title attribute\nexport type CardProps = React.ComponentProps\u003C'div'> & {\n  title: string; \u002F\u002F This conflicts with the HTML title attribute\n};\n\n\u002F\u002F ✅ Good - use a different name\nexport type CardProps = React.ComponentProps\u003C'div'> & {\n  heading: string;\n};\n```\n\n### 3. Document Custom Props\n\nAdd JSDoc comments to custom props for better developer experience:\n\n```tsx\nexport type DialogProps = React.ComponentProps\u003C'div'> & {\n  \u002F** Whether the dialog is currently open *\u002F\n  open: boolean;\n  \u002F** Callback when the dialog requests to be closed *\u002F\n  onOpenChange: (open: boolean) => void;\n  \u002F** Whether to render the dialog in a portal *\u002F\n  modal?: boolean;\n};\n```\n",{"name":5,"description":7},"main","2af107c35457ccaaa2c99d5478745496095d3cf7",".codex\u002Fskills\u002Fcomponents","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc","Certified Pediatrician and IBCLC","2026-03-22 21:33:09",{"source":8,"skillName":5,"commands":45,"prompt":55,"zipAvailable":56},[46,49,52],{"tool":47,"command":48},"npx","npx skills add drhazemibclc\u002Fplate --skill components",{"tool":50,"command":51},"bunx","bunx skills add drhazemibclc\u002Fplate --skill components",{"tool":53,"command":54},"pnpm","pnpm dlx skills add drhazemibclc\u002Fplate --skill components","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fcomponents\u002FSKILL.md",true,[],[59,76,92,105,118,129],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":32},"01M6H97EF29WFNJJJH91670GQ1","workflows-work","[DEPRECATED] Use \u002Fce:work instead — renamed for clarity.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fworkflows-work\u002FSKILL.md",[],[66,67,68,69,31,70,71,72,73,26,74,75],"workflows","work","workflows work","file","path","true","todo","specification","clarity","plan",{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":32},"01M6H97C6CZMYST83WEJN87CVS","workflows-review","[DEPRECATED] Use \u002Fce:review instead — renamed for clarity.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fworkflows-review\u002FSKILL.md",[],[83,84,66,74,85,86,87,31,88,71,89,90,91,26],"workflows review","review","pr","github","branch","latest","number","URL","name",{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":32},"01M6H97A2P4ZE58BKMVQBYAK3M","workflows-plan","[DEPRECATED] Use \u002Fce:plan instead — renamed for clarity.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fworkflows-plan\u002FSKILL.md",[],[66,99,75,100,101,31,71,27,102,74,103,104,26],"workflows plan","bug","improvement","idea","report","bug report",{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":32},"01M6H9780WX39EB980F69WFHEQ","workflows-compound","[DEPRECATED] Use \u002Fce:compound instead — renamed for clarity.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fworkflows-compound\u002FSKILL.md",[],[112,113,66,71,114,31,115,26,116,74,117],"workflows compound","compound","context","about","fix","brief",{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":32},"01M6H9761C1HS173TW6P4ZMCY2","workflows-brainstorm","[DEPRECATED] Use \u002Fce:brainstorm instead — renamed for clarity.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fworkflows-brainstorm\u002FSKILL.md",[],[125,66,126,74,127,26,31,71,128,27,102],"brainstorm","workflows brainstorm","explore","problem",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":32},"01M6H971R100F94DW8NGC93KQ6","vercel-react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fvercel-react-best-practices\u002FSKILL.md",[],[136,137,138,139,19,140,141,142,143,144,145,146,147,148,149,150,151,5,152,153],"vercel","react best practices","best practices","vercel react best practices","Next.js","data fetching","triggers","pages","next","performance optimization","refactoring","Optimization","code","tasks","guidelines","react components","performance","writing"]