Polymorphic Components with 'as' Prop
Type the 'as' prop so a Button renders as or while preserving correct prop types.
What Is a Polymorphic Component?
A polymorphic component renders as different HTML elements or components based on an as prop — e.g., a Button that renders as <a> or <button> while keeping correct TypeScript types.
Simple as Prop (Without TypeScript)
A basic polymorphic implementation without generics — loses type safety but shows the concept.
function Box({ as: Tag = 'div', children, ...props }) {
return <Tag {...props}>{children}</Tag>;
}
// Usage:
<Box as="section" className="hero">...</Box>
<Box as="article">...</Box>All lessons in this course
- Discriminated Unions for Component Variants
- Conditional & Mapped Types in React
- Polymorphic Components with 'as' Prop
- Type-Safe Forms & API Response Contracts