TL;DR: Learn how to architect a scalable, accessible enterprise design system by combining Radix UI's headless primitives with Tailwind CSS. This guide covers creating a
cnutility usingclsxandtailwind-mergeto resolve class conflicts, mapping semantic CSS variables to Tailwind v4 theme tokens for theming, and building polymorphic components with Radix'sSlot.
Key Takeaways
- Use Radix UI's unstyled primitives to handle WAI-ARIA patterns, focus trapping, and portal rendering without fighting opinionated component libraries.
- Implement a
cnutility combiningclsxandtailwind-mergeso a consumer's classes replace conflicting default Tailwind classes. - Define semantic design tokens as CSS variables (e.g.,
--primary: hsl(221.2 83.2% 53.3%);) for light and dark themes in your global CSS. - Map those variables to Tailwind v4 theme variables with
@theme inlinein CSS, so utilities likebg-primaryandbg-primary/90follow the active theme without atailwind.config.js. - Utilize Radix UI's
Slotprimitive to build polymorphic components, allowing a standard<Button>to render as an<a>tag or Next.js<Link>without duplicating styles.
You have been tasked with standardizing the UI across your company's suite of React applications. At first, your team might attempt to build custom components from scratch using standard React state and CSS. Within weeks, you are buried in edge cases: the custom select dropdown gets cut off by overflow: hidden containers, your modals fail to trap focus for screen readers, and keyboard navigation on your tabs does not work.
Frustrated, you consider migrating to a large component library like Material UI or Ant Design. But as soon as the design team hands over a highly bespoke, brand-specific Figma file, you realize those libraries will fight you at every turn. You will spend more time overriding deeply nested CSS classes than writing actual product features.
This is where headless UI components help. By separating accessibility and behavior from visual styling, we can build a design system that scales across teams. In this guide, we will architect a component library using Radix UI for unstyled, accessible logic and Tailwind CSS for design-token-driven styling. The examples use Tailwind CSS v4, which moves theme configuration from tailwind.config.js into CSS.
The Architectural Foundation: Why This Stack?
When building a design system, developers often underestimate how much logic it takes to implement WAI-ARIA patterns correctly. A seemingly simple <Select> component requires handling click-outside events, portal rendering, typeahead search, and arrow-key navigation.
Radix UI addresses this by providing unstyled React components that manage these DOM interactions. Tailwind CSS complements this by allowing us to colocate our styles and enforce design tokens (colors, spacing, typography) without writing sprawling CSS modules.
Let's install the dependencies required to build our foundation:
npm install @radix-ui/react-slot @radix-ui/react-dialog @radix-ui/react-select
npm install class-variance-authority clsx tailwind-merge lucide-react
# Tailwind v4 plus its Vite plugin (use @tailwindcss/postcss for Next.js)
npm install -D tailwindcss @tailwindcss/vite tw-animate-css
Radix also publishes all primitives in a single radix-ui package if you prefer one dependency. tw-animate-css is the Tailwind v4 replacement for the older tailwindcss-animate plugin, which relies on the v3 JavaScript plugin system.
The cn Utility
Before building any components, we need a reliable way to dynamically merge Tailwind classes. If a developer passes a custom className to our button, it should replace the conflicting default styles.
Create a lib/utils.ts file:
// lib/utils.ts
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
Why this matters:
clsxhandles conditional class logic (e.g.,{'opacity-50': disabled}), whiletailwind-mergeunderstands Tailwind's utility hierarchy. WithouttwMerge, if your default button haspx-4and a consumer passespx-2, both classes end up on the element, and the winner is decided by which rule comes later in the generated stylesheet, not by the order in theclassattribute.twMergeremovespx-4sopx-2applies.
Configuring Tailwind for Enterprise Design Tokens
Hardcoding colors like bg-blue-500 throughout your components is a recipe for technical debt. When the brand changes, you don't want to run a project-wide find-and-replace. Instead, we use CSS variables mapped to semantic Tailwind tokens. Setting up semantic tokens before building components is a worthwhile first step in any web application project with more than one theme or product.
Define your raw values as plain CSS variables for each theme, then map them to Tailwind theme variables with @theme inline. In Tailwind v4 this all lives in CSS; there is no tailwind.config.js to maintain. @theme inline makes bg-primary compile to var(--primary) directly, so switching the .dark class switches every utility. Opacity modifiers such as bg-primary/90 are compiled with color-mix(), so the variables can hold complete color values (hsl(...), oklch(...) or hex):
/* styles/globals.css */
@import 'tailwindcss';
@import 'tw-animate-css';
/* Drive dark: utilities from a .dark class instead of the OS preference */
@custom-variant dark (&:where(.dark, .dark *));
:root {
--background: hsl(0 0% 100%);
--foreground: hsl(222.2 84% 4.9%);
--primary: hsl(221.2 83.2% 53.3%);
--primary-foreground: hsl(210 40% 98%);
--accent: hsl(210 40% 96.1%);
--accent-foreground: hsl(222.2 47.4% 11.2%);
--muted-foreground: hsl(215.4 16.3% 46.9%);
--border: hsl(214.3 31.8% 91.4%);
--input: hsl(214.3 31.8% 91.4%);
--ring: hsl(221.2 83.2% 53.3%);
--radius: 0.5rem;
}
.dark {
--background: hsl(222.2 84% 4.9%);
--foreground: hsl(210 40% 98%);
--primary: hsl(217.2 91.2% 59.8%);
--primary-foreground: hsl(222.2 47.4% 11.2%);
--accent: hsl(217.2 32.6% 17.5%);
--accent-foreground: hsl(210 40% 98%);
--muted-foreground: hsl(215 20.2% 65.1%);
--border: hsl(217.2 32.6% 17.5%);
--input: hsl(217.2 32.6% 17.5%);
--ring: hsl(217.2 91.2% 59.8%);
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-muted-foreground: var(--muted-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--radius-lg: var(--radius);
--radius-md: calc(var(--radius) - 2px);
--radius-sm: calc(var(--radius) - 4px);
}
Tailwind v4 also detects your source files automatically, so the v3 content array is no longer needed for files inside your project.
Building a Scalable, Polymorphic Button
A button is never just a button. Sometimes it needs to act as a link (<a>), or it needs to work with Next.js's <Link> component. Radix provides a primitive called Slot that enables polymorphic components: components that can render as different HTML elements while retaining their styled behavior.
We will use class-variance-authority (cva) to define our styling variants cleanly.
// components/ui/button.tsx
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const buttonVariants = cva(
'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
destructive: 'bg-red-500 text-white shadow-sm hover:bg-red-500/90',
outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-8',
icon: 'h-9 w-9',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : 'button';
return (
<Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />
);
},
);
Button.displayName = 'Button';
export { Button, buttonVariants };
Production Note: When
asChildis true, Radix'sSlotmerges the button's props, classes and event handlers onto its single child element. This means<Button asChild><a href="/login">Login</a></Button>renders a styled<a>tag instead of an<a>nested inside a<button>, which would be invalid HTML. The child must accept and spread props (and forward refs) for this to work.
The components here use React.forwardRef, which works in React 18 and 19. In React 19, ref is a regular prop for function components and forwardRef is no longer required, so you can drop the wrapper once you no longer support React 18.
Taming Complexity: The Accessible Dialog (Modal)
Building a custom modal usually involves a z-index arms race and managing complex overlay state. Furthermore, screen reader users often find themselves navigating the background page even when a modal is open. Radix's Dialog primitive handles focus trapping, scroll locking, Escape to close, and the dialog ARIA roles and labelling for you. Add a DialogPrimitive.Title (and ideally a Description) inside each dialog; Radix warns in development when the title is missing.
By combining Radix with Tailwind, we can wrap this primitive in a reusable, styled component.
// components/ui/dialog.tsx
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-[50%] data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-[50%] data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
export { Dialog, DialogTrigger, DialogContent };
Notice the heavy use of data-[state=open] attributes in the Tailwind classes. Radix exposes these data attributes automatically based on the internal state machine of the component. We use these attributes with the tw-animate-css utilities (animate-in, fade-in-0, zoom-in-95 and so on) for entrance and exit animations without writing custom keyframes or adding a JavaScript animation library.
Composing the Select Dropdown: Advanced State Management
The <select> HTML element has historically been hard to style consistently across browsers. Teams that build custom dropdowns often discover that replicating native behavior (like pressing 'C' to jump to Canada in a country list) takes significant effort. Newer browsers are adding customizable <select> styling (appearance: base-select), but support is not yet universal.
Radix's Select component lets us fully redesign the visual appearance while keeping keyboard navigation, typeahead and screen reader support.
// components/ui/select.tsx
import * as React from 'react';
import * as SelectPrimitive from '@radix-ui/react-select';
import { ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
'flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-background text-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className,
)}
position={position}
{...props}
>
<SelectPrimitive.Viewport
className={cn(
'p-1',
position === 'popper' &&
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]',
)}
>
{children}
</SelectPrimitive.Viewport>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent };
Warning: Pay close attention to
SelectPrimitive.Portal. Portals render the dropdown menu outside the immediate DOM hierarchy (usually appending it directly to the<body>). This prevents the dropdown from being clipped byoverflow: hiddenparent containers, a common bug in homegrown UI systems.
Exposing the Library: Monorepos and Exports
Once you have built out your core primitives (Buttons, Inputs, Cards, Dialogs, Selects), the next step in enterprise architecture is distribution. Rather than copying and pasting these files across micro-frontends, standard practice is to wrap this in a Turborepo or Nx monorepo as an internal package (e.g., @acme/ui).
To distribute this package cleanly, configure your package.json exports:
{
"name": "@acme/ui",
"version": "1.0.0",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": "./dist/index.js",
"./button": "./dist/components/button.js",
"./dialog": "./dist/components/dialog.js",
"./select": "./dist/components/select.js",
"./styles.css": "./dist/styles.css"
},
"peerDependencies": {
"react": "^18.2.0 || ^19.0.0",
"react-dom": "^18.2.0 || ^19.0.0",
"tailwindcss": "^4.0.0"
}
}
Because Tailwind v4 skips node_modules when scanning for class names, each consuming app must register the package so the classes used inside it are generated:
/* apps/web/app.css */
@import 'tailwindcss';
@source '../../node_modules/@acme/ui';
This configuration allows consuming applications to import only what they need (import { Button } from '@acme/ui/button'), which helps bundle sizes and gives every team the same components.
The combination of Radix UI and Tailwind CSS gives your team much of the speed of a pre-built component library while keeping full control over the visual design. You avoid fighting pre-packaged styles and start from accessible behavior. Accessibility still depends on how you use the primitives (labels, titles, color contrast), so test with a keyboard, a screen reader and an automated checker such as axe.
Sources
- Tailwind CSS: Theme variables (@theme and @theme inline)
- Tailwind CSS: Dark mode (@custom-variant)
- Tailwind CSS: Detecting classes in source files (@source)
- tw-animate-css on GitHub
- Radix Primitives: Dialog
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Why should I use Radix UI instead of a pre-built component library like Material UI?
Pre-built libraries like Material UI can be hard to bend to a highly bespoke, brand-specific design, because you end up overriding their built-in styles. Radix UI provides headless, unstyled components that handle complex accessibility and behavior logic, allowing you to fully control the visual styling from scratch using Tailwind CSS.
Why is the cn utility function necessary when using Tailwind CSS in React?
The cn function combines clsx for conditional classes and tailwind-merge to resolve Tailwind utility conflicts. Without it, passing a custom class like px-2 to a component with a default px-4 class leaves both on the element, and whichever rule comes later in the generated stylesheet wins, regardless of the order you wrote them.
How do you manage brand colors and design tokens in a Tailwind CSS enterprise design system?
Instead of hardcoding palette classes like bg-blue-500, define semantic CSS variables (such as --primary) per theme in your global stylesheet and map them to Tailwind theme variables with @theme inline. In Tailwind v3 the equivalent mapping lived in tailwind.config.js.
Do I still need raw HSL channel values (without hsl()) in my CSS variables?
Not with Tailwind v4. In Tailwind v3, colors defined as hsl(var(--primary)) needed raw channel values in the variable so opacity modifiers like bg-primary/50 could insert an alpha value. Tailwind v4 compiles opacity modifiers with color-mix(), so the variable can hold a complete color such as hsl(221.2 83.2% 53.3%) or oklch(...).
What are the accessibility benefits of using headless UI components for enterprise applications?
Headless libraries like Radix implement WAI-ARIA patterns for you, such as focus trapping, arrow-key navigation, typeahead and click-outside handling for selects and modals. You still own labels, dialog titles, color contrast and focus styles, so test the final components with a keyboard and a screen reader.
How can I make my React button component polymorphic to work with Next.js links?
You can use the Slot primitive from Radix UI to create polymorphic components. This allows your button component to merge its props and render as a different HTML tag or a Next.js <Link> while keeping all of its default Tailwind styling.
