Sub topic 2
Headless components: behavior without styles
This chapter assumes you can write React function components with hooks, read basic TypeScript, and recognize Tailwind CSS utility classes. It also assumes you know the basic ideas of accessibility: roles, focus, and keyboard operation. The chapter defines what "headless" means, shows the pattern in code, and lists the trade-offs you accept when you use it.
What "headless" means
A headless component supplies behavior and accessibility, and it supplies no visual design. It manages state, keyboard handling, focus, and ARIA attributes. It leaves colors, spacing, borders, and animation to you.
Think of a dropdown menu. A complete one has these parts:
- State: open or closed, and which item is highlighted.
- Keyboard handling: arrow keys move the highlight, Escape closes the menu, and typing a letter jumps to a matching item.
- Focus management: focus moves into the menu when it opens and returns to the trigger when it closes.
- Semantics: roles such as
menuandmenuitem, plus attributes such asaria-expanded. - Appearance: everything you can see.
A conventional component library ships all five parts as one unit. A headless library ships only the first four. You write the fifth.
Why separate behavior from style
The behavior of a menu or dialog is a solved problem. The WAI-ARIA Authoring Practices describe the expected keyboard and screen reader interaction for each widget pattern. Appearance is the opposite. It differs between products and changes with every redesign.
Joining the two causes two recurring problems:
- Override fights. To restyle a conventional library component, you override its CSS or use its theme API. Anything the API does not expose requires selector hacks or
!important. - Accessibility regressions. Teams that avoid override fights by building their own components often skip the hard behavioral details, such as focus trapping or screen reader announcements.
Headless components split these concerns. The library owns the behavior that is hard to get right. You own the markup and styling that your design requires.
Two ways libraries deliver headless behavior
Headless libraries expose behavior in one of two forms.
- Hooks that return props. You call a hook and spread the returned props onto your own elements. Libraries in this style are sometimes called "prop getter" libraries. TanStack Table works like this, though it returns state and rows instead of props.
- Unstyled components. You compose the library's components, which render real DOM elements and accept your
className. Radix UI works like this, and shadcn/ui builds on it.
A hand-written headless hook
A small example shows the hook form. The hook below has no styles. It owns state and the ARIA wiring for a disclosure widget, such as an FAQ item.
import { useId, useState } from "react"
export function useDisclosure(initialOpen = false) {
const [open, setOpen] = useState(initialOpen)
const panelId = useId()
return {
open,
getTriggerProps: () => ({
"aria-expanded": open,
"aria-controls": panelId,
onClick: () => setOpen((value) => !value),
}),
getPanelProps: () => ({
id: panelId,
hidden: !open,
}),
}
}
export function FaqItem() {
const { getTriggerProps, getPanelProps } = useDisclosure()
return (
<div>
<button
type="button"
className="font-medium underline"
{...getTriggerProps()}
>
Shipping
</button>
<p className="mt-2 text-sm text-gray-600" {...getPanelProps()}>
Orders ship within two business days.
</p>
</div>
)
}Three details in this code carry over to every headless library:
- The hook never decides what element to render.
FaqItemchooses a nativebuttonand ap. - The hook returns ARIA attributes, so the relationship between trigger and panel stays correct even if you change the markup.
- A native
buttonalready handles Enter and Space. Choosing the right element is part of the behavior, which is why headless libraries ask you to pass real elements and notdivs.
Spread order matters. In FaqItem, the hook props come after className, so a prop with the same name in the hook output would win. Real libraries return only the props they need, and good ones compose your own handlers with theirs.
Unstyled components: the Radix form
Radix UI primitives take the second approach. Each widget is a set of small components, such as Root, Trigger, Content, and Title. Each renders one element and accepts all standard props for it. This dialog has no styling beyond the classes you see.
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>
)
}With no CSS beyond positioning, this dialog already does the following:
- It moves focus into the content on open and returns it to the trigger on close.
- It traps Tab inside the content while open.
- It closes on Escape and, by default, on a click outside the content.
- It sets
role="dialog"and links the title and description witharia-labelledbyandaria-describedby. - It renders the content through a portal, which attaches it near the end of
document.bodyso parentoverfloworz-indexrules cannot clip it.
The next chapter covers Radix in more detail. The point here is that the appearance is only the className strings.
Styling headless parts by state
Unstyled does not mean you cannot style by state. Headless components expose their state as data attributes on the rendered elements. Radix, for example, sets data-state="open" or data-state="closed". Tailwind can target these directly:
data-[state=open]:bg-gray-100styles an element only while it is open.data-[disabled]:opacity-50styles a disabled item.data-[highlighted]:bg-gray-100styles the item the keyboard has highlighted in a menu.
This gives you a clean rule: the library owns state, and your CSS reads state from attributes. You do not mirror state into your own useState just to choose a class.
Common errors
- Replacing the element and losing behavior. If you render a
divin place of a trigger that expects a button, you must add the role,tabIndex, and key handlers yourself. Prefer the library'sasChildmechanism, covered in a later chapter, to change the element safely. - Forgetting required parts. A Radix dialog without a
Dialog.Titlelogs an accessibility warning in development. The label is part of the contract, so keep the title even if you hide it visually. - Styling away focus. Removing outlines with
outline-noneand providing no replacement makes keyboard users lose their position. Always supply a visible focus style such asfocus-visible:ring-2. - Hiding content with
display: nonemid-animation. Exit animations need the element to remain mounted until the animation ends. Radix supports this through itsdata-stateattributes and, when needed, itsforceMountprop. - Assuming headless means accessible by default. The library handles interaction patterns. It cannot check your color contrast, your label text, or whether your heading order makes sense.
Trade-offs
| Concern | Conventional styled library | Headless library |
|---|---|---|
| Time to a first working screen | Fast, because the design is included | Slower, because you write the styles |
| Custom design fit | Limited by theme options | Unlimited, since you own the classes |
| Behavior and accessibility | Included | Included |
| Visual consistency | Automatic | Your responsibility |
| Markup control | Low | High |
| Upgrade risk | Visual changes may arrive with updates | Behavior changes only |
Headless is a good fit when you have your own design system or need a design that off-the-shelf themes cannot express. It is a weaker fit for an internal tool where speed matters more than appearance. shadcn/ui exists to close that gap. It gives you pre-styled versions of headless parts, which you then own.
Exercise
A teammate replaces the Radix Dialog.Trigger with a div styled like a button, and keyboard users report they can no longer open the dialog. Which part of the headless contract was lost, and what is a safer way to get a different element?
Show answer
The native button supplied keyboard activation (Enter and Space), focus ability, and a button role. A plain div has none of these unless you add role, tabIndex, and key handlers yourself. The safer approach is to keep a real interactive element, for example by passing a link or custom button component with the library's asChild prop, so the library's props and behavior are applied to that element.
Exercise
In the useDisclosure hook, why does getTriggerProps return aria-controls and aria-expanded, and how would you style the trigger differently while the panel is open without adding another useState?
Show answer
aria-expanded tells screen readers whether the controlled panel is shown, and aria-controls names the panel by its id. To style the open state, read the existing open value from the hook, or add data-state={open ? "open" : "closed"} to the returned trigger props and use a Tailwind selector such as data-[state=open]:bg-gray-100.