Sub topic 10
Composing components and using asChild
This chapter assumes you can write React function components with props and hooks, read basic TypeScript, and have already seen the Button and cva code from the earlier chapters. It covers how Radix primitives compose, how asChild changes the element a component renders, and what goes wrong when you use it incorrectly.
Why composition matters
A Radix primitive is split into small parts. A dialog has a root, a trigger, a portal, an overlay, content, a title, a description, and a close control. You assemble these parts yourself. Each part renders one DOM element, and each part shares state with the others through React context.
The shadcn/ui components are thin styled wrappers around these parts. Because you own the wrapper files, you can rearrange the parts, add new ones, or replace the element a part renders.
Replacing the element is the problem asChild solves. Consider a trigger that opens a dialog. By default, Dialog.Trigger renders a <button>. If you put your own styled Button inside it, you get a button nested inside a button:
import * as Dialog from "@radix-ui/react-dialog"
import { Button } from "@/components/ui/button"
// Invalid HTML: a <button> inside a <button>
export function BadTrigger() {
return (
<Dialog.Root>
<Dialog.Trigger>
<Button>Open</Button>
</Dialog.Trigger>
</Dialog.Root>
)
}Nested interactive elements are invalid HTML. They confuse screen readers, and browsers handle clicks and focus on them inconsistently.
What asChild does
Most Radix parts accept an asChild prop. When it is true, the part does not render its own element. It takes its single child element and merges its own props onto that child. These props include event handlers, ref, aria-* attributes, data-* attributes, and type.
import * as Dialog from "@radix-ui/react-dialog"
import { Button } from "@/components/ui/button"
export function GoodTrigger() {
return (
<Dialog.Root>
<Dialog.Trigger asChild>
<Button variant="outline">Open</Button>
</Dialog.Trigger>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/50" />
<Dialog.Content className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-md bg-white p-6">
<Dialog.Title>Settings</Dialog.Title>
<Dialog.Description>Change your preferences.</Dialog.Description>
<Dialog.Close asChild>
<Button>Done</Button>
</Dialog.Close>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
)
}Now the DOM contains one <button>. It has the classes from buttonVariants, and it also has aria-haspopup, aria-expanded, aria-controls, and the click handler that opens the dialog.
How Slot works
Radix implements this with a component called Slot, published as @radix-ui/react-slot. The Button from the shadcn/ui style uses it directly:
const Comp = asChild ? Slot : "button"
return <Comp className={cn(buttonVariants({ variant, size }), className)} ref={ref} {...props} />When asChild is false, Comp is the string "button", and React renders a button. When it is true, Comp is Slot. Slot clones its only child with React.cloneElement and merges the props it received.
The merge follows these rules:
| Prop kind | Merge behavior |
|---|---|
| `className` | Joined, parent and child both kept |
| `style` | Objects merged, child values win on conflict |
| Event handlers | Both run, the child handler first |
| `ref` | Both refs are set |
| Other props | The child's value wins |
Because event handlers are chained, an onClick on your child does not stop the primitive's own onClick from running, unless your handler calls event.preventDefault() and the primitive checks for it. Radix primitives generally check event.defaultPrevented for this reason.
A common use: links styled as buttons
The most frequent use of asChild in a shadcn/ui project is rendering a link with button styles. A link navigates and a button performs an action, so they should stay different elements. asChild lets you share the styles without changing the element:
import Link from "next/link"
import { Button } from "@/components/ui/button"
export function DocsLink() {
return (
<Button asChild variant="outline">
<Link href="/docs">Read the docs</Link>
</Button>
)
}The output is a single <a> element with the button classes. Keyboard users get a native link: Enter activates it, and the browser's "open in new tab" behavior still works. If you had used onClick with router.push on a real <button>, you would lose that behavior.
Rules your child component must follow
Slot passes props down, so the child has to accept them. Three rules apply.
- Render exactly one child element.
SlotcallsReact.Children.only. Two siblings, a string, or a fragment will throw or fail to merge. - Forward the ref. If the child is a function component and does not use
forwardRef, Radix cannot attach its ref. Focus management and positioning then break without an error. In React 19,refis a normal prop for function components, so this applies mainly to React 18 projects. - Spread the rest props onto the DOM element. If your child accepts
classNamebut drops...props, thearia-*attributes and handlers never reach the DOM.
Here is a child that breaks the contract, followed by a fixed version:
import * as React from "react"
// Broken: ignores ref and rest props
function BrokenLink({ children }: { children: React.ReactNode }) {
return <a href="/docs">{children}</a>
}
// Fixed: forwards ref and spreads props
const DocsAnchor = React.forwardRef<
HTMLAnchorElement,
React.AnchorHTMLAttributes<HTMLAnchorElement>
>(({ children, ...props }, ref) => (
<a href="/docs" ref={ref} {...props}>
{children}
</a>
))
DocsAnchor.displayName = "DocsAnchor"Use BrokenLink inside <Button asChild> and the button classes silently disappear. The cause is that className is passed to BrokenLink, which discards it.
Composing several primitives on one element
You can stack asChild to attach behavior from more than one primitive to the same element. A common case is a button that opens a dropdown menu and also shows a tooltip:
import * as DropdownMenu from "@radix-ui/react-dropdown-menu"
import * as Tooltip from "@radix-ui/react-tooltip"
import { Button } from "@/components/ui/button"
export function MenuWithTooltip() {
return (
<Tooltip.Provider>
<DropdownMenu.Root>
<Tooltip.Root>
<Tooltip.Trigger asChild>
<DropdownMenu.Trigger asChild>
<Button variant="outline">Options</Button>
</DropdownMenu.Trigger>
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content className="rounded-md bg-black px-2 py-1 text-xs text-white">
Open the options menu
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
<DropdownMenu.Portal>
<DropdownMenu.Content className="rounded-md border bg-white p-1">
<DropdownMenu.Item className="px-2 py-1 text-sm">Rename</DropdownMenu.Item>
<DropdownMenu.Item className="px-2 py-1 text-sm">Delete</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
</Tooltip.Provider>
)
}Each Slot merges onto the next one down, and the final Button receives the combined props. This only works because every layer forwards its ref and its props.
Composition patterns beyond asChild
asChild is one tool. Three other patterns appear often in shadcn/ui code.
- Compound components. Parts such as
DialogTriggerandDialogContentare separate exports that share state through context. You choose which parts to render and in what order. - Wrapper components. A wrapper such as
ConfirmDialoghides the parts behind a smaller API. This is useful when many screens repeat the same structure. - Context across levels. Parts must sit inside their root. A
Dialog.TitleoutsideDialog.Rootthrows an error, because it cannot find the context.
Prefer a wrapper when you repeat the same composition three or more times. Prefer direct composition when each use differs.
Gotchas
- Disabled state. A disabled
<button>ignores clicks. A disabled link does not exist in HTML. If you useButton asChildwith a link,disabledhas no effect on the<a>. Usearia-disabled="true"and block navigation yourself, or render a real<button>instead. - Wrong semantics.
asChildlets you put trigger behavior on a<div>. The div will not be focusable and will not respond to Enter or Space. Always pick an element with the right native semantics. - Conditional children.
{cond && <Button />}can yieldfalse, whichSlotcannot clone. Keep the child present. - Class conflicts.
Slotjoins class names but does not resolve Tailwind conflicts. Pass shared classes throughcnin the child sotailwind-mergecan remove duplicates.
Exercise
A teammate writes <Dialog.Trigger asChild><span>Open</span></Dialog.Trigger> and reports that keyboard users cannot open the dialog. Explain why, and give a fix.
Show answer
With asChild, Slot merges the trigger's props onto the span, but a span is not focusable and does not turn Enter or Space into a click. The click handler is attached, so mouse users can open the dialog, but keyboard users cannot reach it. The fix is to pass an element with native button semantics, for example <Dialog.Trigger asChild><Button>Open</Button></Dialog.Trigger>, or to drop asChild and let the trigger render its default <button>.
Exercise
You wrap an internal Card component as <Tooltip.Trigger asChild><Card /></Tooltip.Trigger>. The tooltip never appears. Name two likely causes in Card.
Show answer
First, Card may not forward its ref, so the tooltip cannot measure or attach to the element. Second, Card may not spread its rest props onto the DOM element, so the event handlers and aria attributes from the trigger never reach it. Fixing both with forwardRef and {...props} resolves it.