Sub topic 4
Radix UI primitives in practice
Radix UI primitives are unstyled React components that handle behavior and accessibility. shadcn/ui builds its components on top of them. This chapter assumes you know React function components, props, and hooks, basic TypeScript, and how to install packages in a Vite or Next.js project. It also assumes you have read the earlier chapters on accessibility and headless components. Here you will use a primitive directly, see what it does for you, and learn the patterns that matter when shadcn/ui wraps it.
What a primitive gives you
Each Radix package covers one interaction pattern, such as a dialog, dropdown menu, tabs, or tooltip. You install only what you use:
npm install @radix-ui/react-dialogA primitive is a set of parts that you assemble yourself. It owns the state machine, keyboard handling, focus management, and ARIA attributes. It ships no CSS, so every visual choice is yours.
import * as Dialog from "@radix-ui/react-dialog"
export function ConfirmDialog() {
return (
<Dialog.Root>
<Dialog.Trigger>Delete item</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>Delete this item?</Dialog.Title>
<Dialog.Description>This action cannot be undone.</Dialog.Description>
<Dialog.Close>Cancel</Dialog.Close>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
)
}The classes on the overlay and content are the only styling. Everything else comes from Radix.
The parts of a dialog
Parts are separate components that share state through React context. This is the compound component pattern, and every Radix primitive uses it.
| Part | Renders | What it does |
|---|---|---|
| `Root` | Nothing | Holds the open state and shares it with the other parts |
| `Trigger` | `button` | Toggles the dialog and sets `aria-expanded` and `aria-controls` |
| `Portal` | Nothing of its own | Moves its children to the end of `document.body` |
| `Overlay` | `div` | Covers the page behind the dialog |
| `Content` | `div` with `role="dialog"` | Traps focus, closes on Escape, and links to the title and description |
| `Title` | `h2` | Names the dialog through `aria-labelledby` |
| `Description` | `p` | Describes the dialog through `aria-describedby` |
| `Close` | `button` | Closes the dialog |
Because Root renders no element, it adds nothing to your layout. The other parts must be descendants of Root, or they cannot read its state.
What Radix does at runtime
When the dialog opens, Radix runs several behaviors at once:
- It moves focus into
Content, to the first focusable element. - It keeps Tab and Shift+Tab inside the dialog (a focus trap).
- It closes the dialog on Escape or on a click outside
Content. - It prevents the page behind the dialog from scrolling.
- It hides the content outside the dialog from screen readers.
- When the dialog closes, it returns focus to the trigger.
Returning focus is easy to overlook. Without it, a keyboard user who closes a dialog lands at the top of the page and loses their place.
Styling with data attributes
Radix exposes its internal state as data-* attributes on the rendered elements. The dialog parts set data-state to open or closed. Other primitives add more. A tab has data-state="active", and a menu item has data-highlighted when it is focused by keyboard or pointer.
Tailwind can target these attributes directly:
<Dialog.Overlay className="fixed inset-0 bg-black/50 data-[state=open]:opacity-100 data-[state=closed]:opacity-0 transition-opacity" />shadcn/ui components use this pattern heavily. You will see classes such as data-[state=open]:animate-in in the files the CLI copies into your project.
Controlled and uncontrolled state
By default, Root manages its own open state. You can start it open with defaultOpen. To drive it from your own state, pass open and onOpenChange:
import { useState } from "react"
import * as Dialog from "@radix-ui/react-dialog"
export function DeleteDialog({ onConfirm }: { onConfirm: () => Promise<void> }) {
const [open, setOpen] = useState(false)
const [pending, setPending] = useState(false)
async function handleConfirm() {
setPending(true)
try {
await onConfirm()
setOpen(false)
} finally {
setPending(false)
}
}
return (
<Dialog.Root open={open} onOpenChange={setOpen}>
<Dialog.Trigger>Delete item</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>Delete this item?</Dialog.Title>
<Dialog.Description>This action cannot be undone.</Dialog.Description>
<button type="button" onClick={handleConfirm} disabled={pending}>
{pending ? "Deleting..." : "Delete"}
</button>
<Dialog.Close>Cancel</Dialog.Close>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
)
}Use controlled state when the dialog must stay open during an async action, or when other code needs to open it, such as a keyboard shortcut. Otherwise leave it uncontrolled, because it needs less code.
Do not switch a component between controlled and uncontrolled during its lifetime. Passing open={undefined} on the first render and a boolean later causes the same kind of problem as it does with a native input.
Common errors
Most problems with Radix come from a few causes.
- Missing Title.
Dialog.Contentneeds aDialog.Title. Without one, a screen reader announces an unnamed dialog, and Radix logs a console warning in development. If the design has no visible title, wrap the title in a visually hidden element rather than removing it. - Parts outside Root. A
Dialog.Triggerrendered outsideDialog.Rootthrows an error about missing context. - Styles that do not reach the content.
Portalmoves the content todocument.body. CSS selectors that depend on an ancestor in your component tree stop matching. A parent's.card .dialogrule will not apply, and neither will a Tailwindgroup-hoveron that parent. Style the content directly. - Z-index conflicts. Portaled content sits at the end of the body. A positioned element elsewhere with a higher
z-indexcan still draw on top. Set an explicitz-indexon the overlay and content. - Wrapper elements that break behavior. Radix attaches handlers and refs to the element it renders. If you replace that element with a custom component, the component must forward its
refand spread its props onto a DOM node.
Changing the rendered element
Each part renders a default element, such as a button for Trigger. Sometimes you want a different element with the same behavior, for example your own styled button component. Every Radix part accepts an asChild prop. When it is set, Radix does not render its own element. It merges its props, handlers, and ref onto the single child you pass:
<Dialog.Trigger asChild>
<button type="button" className="rounded-md border px-4 py-2">
Delete item
</button>
</Dialog.Trigger>This is how shadcn/ui lets a Button act as a trigger. A later chapter covers asChild and composition in detail.
Why shadcn/ui builds on primitives
Writing the focus trap, ARIA wiring, and keyboard handling yourself is slow and easy to get wrong. A primitive removes that work and leaves you only the styling. shadcn/ui adds a styled wrapper around each primitive and copies it into your project. When you read components/ui/dialog.tsx after running the CLI, you will see the same parts you used here, re-exported with Tailwind classes attached.
Exercise
You wrap Dialog.Content in your own component, Panel, which renders a div but does not forward ref or spread its props. Which two Radix behaviors are likely to break, and what two changes fix it?
Show answer
Focus management and dismissal behaviors such as Escape handling and the ARIA wiring may stop working, because Radix cannot attach its ref and handlers to the DOM node. Fix it by making Panel forward its ref with React.forwardRef and spread the received props onto the div. Alternatively, pass your element as the child of Dialog.Content asChild, which also merges Radix's props onto it, as long as the element forwards them to a DOM node.
Exercise
A dialog's backdrop should fade out over 150 ms when it closes. Which attribute do you target in Tailwind, and what happens if you only style the open state?
Show answer
Target data-[state=closed], for example data-[state=closed]:opacity-0 together with transition-opacity duration-150. Radix keeps the element mounted while the exit animation or transition runs. If you only style the open state, there is nothing to animate toward, so the overlay disappears immediately.