Skip to main content
rule CX Codex

polymorphism — Claude Code rule: what it does, how to install

polymorphism is a Claude Code rule for React components that keep their styles and behavior across element types. The as prop selects the rendered element.

Apache-2.0 ★ 141 updated 2026-11-17

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/polymorphism.md
Open on GitHub

What polymorphism does

The polymorphism rule defines React components that can switch their rendered HTML element or component while keeping shared styles and behavior. An as prop can select a, button, div, or a custom component. TypeScript support uses React.ElementType together with React.ComponentPropsWithoutRef so the selected element's props can be carried through.

Examples cover typography, layout, and interactive components. The rule favors semantic defaults such as article, nav, and h2, then adds accessibility details with role, tabIndex, keyboard handling, and aria-label. A nested button remains invalid HTML, as does placing a div inside a paragraph.

For Claude Code, add .claude/rules/polymorphism.md; Cursor uses .cursor/rules/polymorphism.mdc, GitHub Copilot uses .github/instructions/polymorphism.instructions.md, Windsurf uses .devin/rules/polymorphism.md, and Cline uses .clinerules/polymorphism.md. A custom component reference should stay stable, since defining it inside a parent render creates a new component each time.

What it helps with

  • switch a component between semantic HTML elements
  • keep Text styling while rendering it as h1 or p
  • type an as prop and its element-specific properties in TypeScript
  • add keyboard behavior to a non-button interactive element
  • prevent invalid HTML nesting in reusable components

Example prompts for the agent

  • Build a Button that renders as a with href or as button with type.
  • Refactor Text so as="h1" keeps the heading variant and its styles.
  • Review this polymorphic component for keyboard access, ARIA attributes, and invalid element nesting.

How to install polymorphism

Manually: put the files in place

.claude/rules/polymorphism.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about polymorphism

How do I install polymorphism in Claude Code?

Create .claude/rules/polymorphism.md and place the rule content in that file.

What does polymorphism do?

It describes React components that can render different HTML elements through an as prop while retaining shared styling, behavior, and TypeScript prop types.

How does polymorphism address accessibility?

It recommends semantic elements, an aria-label for navigation, and role, tabIndex, and keyboard handling when an interactive component is rendered as something other than button or a.

Source text

polymorphism.md · Apache-2.0
---
title: Polymorphism Patterns
impact: MEDIUM
impactDescription: Flexible element rendering
tags: polymorphism, as-prop, element-type, typescript, semantic-html
---

## Polymorphism Patterns

Build flexible components that can render as different HTML elements or components while maintaining consistent styling and behavior.

### Core Pattern: The `as` Prop

The `as` prop allows components to change their rendered element type:

```tsx
<Button as="a" href="/home">Go Home</Button>
<Button as="button" type="submit">Submit</Button>
<Button as="div" role="button" tabIndex={0}>Custom Element</Button>
```

### Basic Implementation

```tsx
function Component({ as: Element = "div", children, ...props }) {
  return <Element {...props}>{children}</Element>;
}
```

### TypeScript Implementation

```tsx
type PolymorphicProps<E extends React.ElementType> = {
  as?: E;
  children?: React.ReactNode;
} & React.ComponentPropsWithoutRef<E>;

function Component<E extends React.ElementType = "div">({
  as,
  children,
  ...props
}: PolymorphicProps<E>) {
  const Element = as || "div";
  return <Element {...props}>{children}</Element>;
}
```

### Common Use Cases

**Typography Components:**

```tsx
function Text({ as: Element = 'span', variant = 'body', ...props }) {
  const className = cn(
    'text-base',
    variant === 'heading' && 'text-2xl font-bold',
    variant === 'body' && 'text-base',
    props.className
  );
  return <Element className={className} {...props} />;
}

<Text as="h1" variant="heading">Title</Text>
<Text as="p" variant="body">Paragraph</Text>
```

**Layout Components:**

```tsx
function Flex({ as: Element = 'div', ...props }) {
  return <Element className={cn('flex', props.className)} {...props} />;
}

<Flex as="header" className="justify-between"><Logo /><Navigation /></Flex>
<Flex as="main" className="flex-col"><Content /></Flex>
```

**Interactive Elements:**

```tsx
function Clickable({ as: Element = "button", ...props }) {
  const isButton = Element === "button";
  const isAnchor = Element === "a";
  return (
    <Element
      role={!isButton && !isAnchor ? "button" : undefined}
      tabIndex={!isButton && !isAnchor ? 0 : undefined}
      {...props}
    />
  );
}
```

### Best Practices

**1. Default to Semantic Elements:**

**Incorrect (too generic):**

```tsx
function Component({ as: Element = "div", ...props }) {}
```

**Correct (semantic defaults):**

```tsx
function Article({ as: Element = "article", ...props }) {}
function Navigation({ as: Element = "nav", ...props }) {}
function Heading({ as: Element = "h2", ...props }) {}
```

**2. Document Valid Elements:**

```tsx
interface BoxProps {
  /**
   * The HTML element to render as
   * @default 'div'
   */
  as?: "div" | "section" | "article" | "aside" | "main" | "header" | "footer";
}
```

**3. Handle Event Handlers:**

```tsx
function Interactive({ as: Element = "button", onClick, ...props }) {
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (Element !== "button" && (e.key === "Enter" || e.key === " ")) {
      onClick?.(e as any);
    }
  };
  return (
    <Element
      onClick={onClick}
      onKeyDown={Element !== "button" ? handleKeyDown : undefined}
      {...props}
    />
  );
}
```

### Common Pitfalls

**Invalid HTML Nesting:**

```tsx
// Incorrect: Invalid - button inside button
<Button as="button"><Button as="button">Nested</Button></Button>

// Incorrect: Invalid - div inside p
<Text as="p"><Box as="div">Invalid</Box></Text>

// Correct: Valid nesting
<Text as="div"><Box as="div">Valid</Box></Text>
```

**Missing Accessibility:**

```tsx
// ❌ Missing accessibility
<Box as="nav"><MenuItems /></Box>

// ✅ Proper accessibility
<Box as="nav" aria-label="Main navigation"><MenuItems /></Box>
```

**Performance:**

```tsx
// ❌ Creates new component on every render
function Parent() {
  const CustomDiv = (props) => <div {...props} />;
  return <Component as={CustomDiv} />;
}

// ✅ Stable component reference
const CustomDiv = (props) => <div {...props} />;
function Parent() {
  return <Component as={CustomDiv} />;
}
```

### Key Benefits

1. **Semantic HTML Flexibility** - Use the most appropriate element
2. **Component Reusability** - One component serves multiple purposes
3. **Accessibility** - Choose elements for best accessibility
4. **Style System Integration** - Maintain styling while changing elements

© maxtrigify · Apache-2.0 · maxtrigify/Otto

Similar IDE rules

All IDE rules for Frontend and UI →

From the same set18

The whole set →
as-child as-child is a Claude Code rule for merging a component’s props and handlers into a custom child without an extra DOM wrapper. It applies to composable React triggers. CX Codex +1 ★ 141repo stars documentation documentation is a Claude Code rule that standardizes UI component documentation. It enforces consistent sections for props, runnable examples, and accessibility guidelines. CX Codex +1 ★ 141repo stars state state is a Claude Code rule for controlled and uncontrolled React component state. It applies while designing component APIs and state props. CX Codex +1 ★ 141repo stars accessibility accessibility is a Claude Code rule that enforces accessible frontend patterns. It triggers when generating UI components, dialogs, and navigation menus. CX Codex +1 ★ 141repo stars styling styling is a Claude Code rule that enforces Tailwind CSS patterns. Guides the agent to combine classes with tailwind-merge, clsx, and CVA. CX Codex +1 ★ 141repo stars definitions definitions is a Claude Code rule that classifies UI artifacts and keeps names consistent across primitives, components, blocks, templates, and patterns. CX Codex +1 ★ 141repo stars components-build components-build is a Claude Code skill for building, reviewing, and refactoring reusable React components with the components.build specification. It activates for work on component APIs, accessibility, styling, and TypeScript props. CX Codex +1 ★ 141repo stars otto-design otto-design is a Claude Code skill that enforces UI mockup creation in Paper before building SwiftUI views. It triggers on redesigns, mockups, or any visual changes to Otto surfaces. CX Codex +1 ★ 141repo stars

Project sponsors

Companies that keep this analytics open