Course contentsShow
← React
Lesson 1105 of 2,39628. Composition: Compound ComponentsFree lesson

Composing Custom Components with Library Primitives

Build your own compound components by wrapping Radix or Headless UI primitives with custom logic.

Composing Custom Components with Library Primitives

What You'll Learn

You'll learn how to wrap Radix UI or Headless UI primitives inside your own custom components to combine library-provided functionality with your application-specific logic and styling.

The Core Idea

Libraries like Radix and Headless UI provide low-level "primitive" components that handle complex behavior (accessibility, keyboard navigation, focus management) but leave styling and composition to you. By wrapping these primitives in your own components, you create reusable, branded components that maintain all the library's functionality while adding your custom logic, styling, or business rules.

Think of it like buying a high-quality engine (the primitive) and building your own custom car body around it. The engine handles the complex mechanics; you design the exterior and add features your users need.

Building Your Custom Component

// Wrap Radix primitive with custom styling and logic
function MyCustomDialog({ 
  title, 
  children, 
  onConfirm 
}: MyCustomDialogProps) {
  const [isLoading, setIsLoading] = useState(false);

  const handleConfirm = async () => {
    setIsLoading(true);
    await onConfirm();
    setIsLoading(false);
  };

  return (
    <Dialog.Root>
      <Dialog.Trigger className="my-button">
        Open
      </Dialog.Trigger>
      <Dialog.Portal>
        <Dialog.Overlay className="my-overlay" />
        <Dialog.Content className="my-dialog-content">
          <Dialog.Title>{title}</Dialog.Title>
          {children}
          <button onClick={handleConfirm} disabled={isLoading}>
            {isLoading ? 'Processing...' : 'Confirm'}
          </button>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}

Now consumers use <MyCustomDialog> with a simplified API while getting all the accessibility and compound component power from Radix under the hood. You've hidden complexity, added loading states, and applied consistent styling—all without reimplementing dialog behavior from scratch.

Key Takeaway: Wrapping library primitives in custom components lets you combine battle-tested functionality with your application's specific needs, creating a design system that's both powerful and easy to use.