Data Attributes for Styling State
What you'll learn: How to style component states declaratively using data attributes exposed by headless libraries like Radix UI.
The Problem with Dynamic Styling
When building interactive components, you often need to style different states: open vs closed, active vs inactive, disabled vs enabled. You could apply conditional class names based on props, but that means every consumer has to write logic to map state to styles.
Radix's Data Attribute Solution
Radix Primitives automatically attach data attributes to DOM elements based on their internal state. These attributes appear in the HTML and can be targeted directly with CSS selectors:
import * as Dialog from '@radix-ui/react-dialog';
function MyDialog() {
return (
<Dialog.Root>
<Dialog.Trigger>Open</Dialog.Trigger>
<Dialog.Content className="dialog-content">
{/* Radix automatically adds data-state="open" or "closed" */}
Content here
</Dialog.Content>
</Dialog.Root>
);
}
Styling with Data Attributes
Target these attributes in your CSS without writing any JavaScript logic:
.dialog-content[data-state="open"] {
animation: slideIn 200ms;
}
.dialog-content[data-state="closed"] {
animation: slideOut 200ms;
}
.button[data-disabled] {
opacity: 0.5;
cursor: not-allowed;
}
Common Data Attributes
data-state: "open" | "closed" | "active" | "inactive"data-disabled: Present when disableddata-highlighted: Present when keyboard-focused or hovered
This approach is declarative: the library manages state, and your CSS reacts to it. No useState, no conditional logic in your component.
Key Takeaway: Radix components expose state through data attributes like data-state, data-disabled, and data-highlighted, letting you style interactive states purely with CSS selectors instead of JavaScript logic.