0Pricing
React Academy · Lesson

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

  1. Discriminated Unions for Component Variants
  2. Conditional & Mapped Types in React
  3. Polymorphic Components with 'as' Prop
  4. Type-Safe Forms & API Response Contracts
← Back to React Academy