Skip to main content

Lesson 4 of 8

Headless & Polymorphic Components

Headless components provide behavior without enforcing a visual style - think useCombobox from Downshift or useMenu from Radix. Polymorphic components render as any HTML element (`as` prop), enabling semantic flexibility without duplicating logic.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Polymorphic Component with TypeScript

Polymorphic Component with TypeScript
import { type ElementType, type ComponentPropsWithRef, forwardRef } from 'react';

// ---- Polymorphic type helpers ----
// Extracts the props for the given element type, excluding our own props
type PolymorphicProps<E extends ElementType, P = object> = P & {
  as?: E;
} & Omit<ComponentPropsWithRef<E>, keyof P | 'as'>;

// ---- Text component - renders as any element, applies design system styles ----
type TextVariant = 'h1' | 'h2' | 'body' | 'caption' | 'code';

const TEXT_STYLES: Record<TextVariant, React.CSSProperties> = {
  h1: { fontSize: '2rem', fontWeight: 700, lineHeight: 1.2, letterSpacing: '-0.025em' },
  h2: { fontSize: '1.5rem', fontWeight: 600, lineHeight: 1.3 },
  body: { fontSize: '1rem', lineHeight: 1.6, color: '#4b5563' },
  caption: { fontSize: '0.75rem', color: '#6b7280' },
  code: { fontFamily: 'monospace', fontSize: '0.875rem', background: '#f3f4f6', padding: '2px 6px', borderRadius: 4 },
};

const DEFAULT_ELEMENTS: Record<TextVariant, ElementType> = {
  h1: 'h1', h2: 'h2', body: 'p', caption: 'span', code: 'code',
};

type TextProps<E extends ElementType> = PolymorphicProps<E, {
  variant: TextVariant;
}>;

// TS: forwardRef with generics needs a wrapper
function Text<E extends ElementType>({ as, variant, style, ...props }: TextProps<E>) {
  const Component = as ?? DEFAULT_ELEMENTS[variant];
  return (
    <Component
      style={{ ...TEXT_STYLES[variant], ...style }}
      {...props}
    />
  );
}

// Usage
<Text variant="h1">Main Heading</Text>                          // renders <h1>
<Text variant="h1" as="div">Section</Text>                     // renders <div> (override)
<Text variant="body" as="label" htmlFor="email">Email</Text>   // <label> with all label props
<Text variant="code" as="pre">const x = 1;</Text>              // <pre> with code styles

// ---- Headless List with keyboard navigation ----
function useListNavigation({ items, onSelect }: { items: string[]; onSelect: (item: string) => void }) {
  const [activeIndex, setActiveIndex] = useState(-1);

  function getInputProps() {
    return {
      onKeyDown: (e: React.KeyboardEvent) => {
        switch (e.key) {
          case 'ArrowDown':
            e.preventDefault();
            setActiveIndex(i => Math.min(i + 1, items.length - 1));
            break;
          case 'ArrowUp':
            e.preventDefault();
            setActiveIndex(i => Math.max(i - 1, -1));
            break;
          case 'Enter':
            if (activeIndex >= 0) { e.preventDefault(); onSelect(items[activeIndex]); }
            break;
          case 'Escape':
            setActiveIndex(-1);
            break;
        }
      },
    };
  }

  function getItemProps(index: number) {
    return {
      'aria-selected': index === activeIndex,
      onMouseEnter: () => setActiveIndex(index),
      onClick: () => onSelect(items[index]),
      style: { background: index === activeIndex ? '#EDE9FE' : 'transparent' },
    };
  }

  return { activeIndex, getInputProps, getItemProps };
}

Tip

Tip

Practice Headless Polymorphic Components in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and flow for Headless & Polymorphic Components

Practice Task

Note

Practice Task - (1) Write a working example of Headless Polymorphic Components from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Headless Polymorphic Components is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done