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
- Accept an
asprop (defaulting to your base element) - Store it in a variable (commonly called
Component) - Render that variable as a JSX element
- 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.