Course contentsShow
← React
Lesson 1161 of 2,39630. Composition: Inversion of ControlFree lesson

The 'as' Prop Pattern for Component Polymorphism

Letting consumers specify which underlying element or component to render while keeping behavior intact.

The 'as' Prop Pattern for Component Polymorphism

You'll learn how to let consumers choose the underlying HTML element or component your component renders, while preserving all its styling and behavior.

The Core Idea

Sometimes you build a component like <Button> that has great styling and behavior, but consumers need it to render as different things: sometimes a <button>, sometimes an <a> link, sometimes a Next.js <Link>. The 'as' prop pattern lets them specify which element to use without losing your component's features.

Think of it like a costume: your component's behavior and styling are the person underneath, but the as prop lets them wear different "outfits" (HTML tags) depending on the context.

// Your flexible Button component
function Button({ as = 'button', children, ...props }) {
  const Component = as;
  return <Component className="btn-styles" {...props}>{children}</Component>;
}

// Consumer decides what it renders as
<Button>Click me</Button>                    // <button>
<Button as="a" href="/home">Go Home</Button> // <a>
<Button as={Link} to="/about">About</Button> // <Link>

How It Works

  1. Accept an as prop (defaulting to your base element)
  2. Store it in a variable (commonly called Component)
  3. Render that variable as a JSX element
  4. Spread remaining props so element-specific attributes (like href) still work

This is polymorphism: one component interface, multiple underlying implementations.

Why It Matters

This pattern gives consumers control over semantic HTML and routing behavior while you maintain ownership of styling and interaction logic. Libraries like Chakra UI and Radix use this extensively.

Key Takeaway: The 'as' prop pattern inverts control over what renders while keeping how it renders (styling, behavior) in your component's hands—enabling true component polymorphism.