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

Slot-Based Composition in Radix Primitives

Understand Radix's asChild pattern for merging props and behavior onto custom elements.

Slot-Based Composition in Radix Primitives

What you'll learn: How Radix's asChild prop lets you merge component behavior onto your own custom elements without wrapper divs.

The Problem with Traditional Composition

Most compound components render their own DOM elements. When you use <Tabs.Trigger>, it renders a <button>. But what if you want that trigger behavior on your custom <FancyButton> component? Traditionally, you'd nest it and get extra wrappers:

<Tabs.Trigger>
  <FancyButton>Click me</FancyButton>  {/* unnecessary nesting */}
</Tabs.Trigger>

The asChild Pattern

Radix solves this with slot-based composition using the asChild prop. When asChild={true}, the Radix component doesn't render its own element—instead, it merges its props and behavior onto the immediate child you provide:

<Tabs.Trigger asChild>
  <FancyButton>Click me</FancyButton>
</Tabs.Trigger>

Now FancyButton receives all the click handlers, ARIA attributes, and state management from Tabs.Trigger—no wrapper needed!

How It Works

Think of it like a slot machine: the Radix component creates a "slot" where you can insert your own element. The component clones your child element and spreads its props onto it, combining event handlers and data attributes.

Behind the scenes, Radix uses React.cloneElement to merge:

  • Its own event handlers with yours
  • ARIA attributes for accessibility
  • Data attributes for styling hooks
  • State-based props (like aria-selected)

This lets you keep full control over the rendered DOM while getting Radix's compound component behavior.

Key Takeaway: The asChild pattern in Radix Primitives uses slot-based composition to merge component logic onto your custom elements, eliminating wrapper divs and giving you complete control over the rendered markup while preserving compound component functionality.