mirror of
https://github.com/vercel/components.build.git
synced 2026-09-14 20:06:39 +08:00
55fae375a4
* Update Geistdocs * Update geistdocs.tsx * Run translation script * Delete toc.tsx * Update route.ts * Update route.ts
400 lines
12 KiB
Plaintext
400 lines
12 KiB
Plaintext
---
|
|
title: Data-attributen
|
|
description: Data-attributen gebruiken voor declaratieve styling en componentidentificatie.
|
|
---
|
|
|
|
Data-attributen bieden een krachtige manier om de status en structuur van componenten aan consumenten bloot te stellen, waardoor flexibele styling mogelijk is zonder prop-explosie. Moderne componentbibliotheken gebruiken twee primaire patronen: `data-state` voor visuele staten en `data-slot` voor componentidentificatie.
|
|
|
|
## Staten stylen met data-state
|
|
|
|
Een van de meest voorkomende anti-patterns in componentstyling is het blootstellen van afzonderlijke className-props voor verschillende staten.
|
|
|
|
Bij minder moderne componenten zie je vaak API's zoals deze:
|
|
|
|
```tsx
|
|
<Dialog
|
|
openClassName="bg-black"
|
|
closedClassName="bg-white"
|
|
classes={{
|
|
open: "opacity-100",
|
|
closed: "opacity-0"
|
|
}}
|
|
/>
|
|
```
|
|
|
|
Deze aanpak heeft verschillende problemen:
|
|
- Het koppelt de interne staat van de component aan zijn styling-API
|
|
- Het creëert een explosie van props naarmate componenten complexer worden
|
|
- Het maakt de component moeilijker te gebruiken en te onderhouden
|
|
- Het verhindert styling op basis van combinatie van staten
|
|
|
|
### De oplossing: data-state-attributen
|
|
|
|
Gebruik in plaats daarvan `data-*` attributen om componentstatus declaratief bloot te stellen. Dit stelt consumenten in staat componenten te stylen op basis van staat met standaard CSS-selectors:
|
|
|
|
```tsx title="component.tsx"
|
|
const Dialog = ({ className, ...props }: DialogProps) => {
|
|
const [isOpen, setIsOpen] = useState(false);
|
|
|
|
return (
|
|
<div
|
|
data-state={isOpen ? 'open' : 'closed'}
|
|
className={cn('transition-all', className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
};
|
|
```
|
|
|
|
Nu kunnen consumenten de component van buitenaf stylen op basis van staat:
|
|
|
|
```tsx title="app.tsx"
|
|
<Dialog className="data-[state=open]:opacity-100 data-[state=closed]:opacity-0" />
|
|
```
|
|
|
|
### Voordelen van deze aanpak
|
|
|
|
1. **Enkele className-prop** - Geen behoefte aan meerdere state-specifieke className-props
|
|
2. **Compositie** - Combineer meerdere data-attributen voor complexe staten
|
|
3. **Standaard CSS** - Werkt met elke CSS-in-JS-oplossing of gewone CSS
|
|
4. **Typeveilig** - TypeScript kan data-attribuutwaarden afleiden
|
|
5. **Inspecteerbaar** - Staten zijn zichtbaar in DevTools als HTML-attributen
|
|
|
|
### Veelvoorkomende statenpatronen
|
|
|
|
Gebruik data-attributen voor allerlei soorten componentstaten:
|
|
|
|
```tsx
|
|
// Open/closed state
|
|
<Accordion data-state={isOpen ? 'open' : 'closed'} />
|
|
|
|
// Selected state
|
|
<Tab data-state={isSelected ? 'active' : 'inactive'} />
|
|
|
|
// Disabled state (in addition to disabled attribute)
|
|
<Button data-disabled={isDisabled} disabled={isDisabled} />
|
|
|
|
// Loading state
|
|
<Button data-loading={isLoading} />
|
|
|
|
// Orientation
|
|
<Slider data-orientation="horizontal" />
|
|
|
|
// Side/position
|
|
<Tooltip data-side="top" />
|
|
```
|
|
|
|
### Stijlen met Tailwind
|
|
|
|
Tailwind ondersteunt arbitraire variants, waardoor data-attribuutstyling elegant wordt:
|
|
|
|
```tsx
|
|
<Dialog
|
|
className={cn(
|
|
// Base styles
|
|
'rounded-lg border p-4',
|
|
// State-based styles
|
|
'data-[state=open]:animate-in data-[state=open]:fade-in',
|
|
'data-[state=closed]:animate-out data-[state=closed]:fade-out',
|
|
// Multiple attributes
|
|
'data-[state=open][data-side=top]:slide-in-from-top-2'
|
|
)}
|
|
/>
|
|
```
|
|
|
|
Voor veelgebruikte staten kun je de Tailwind-configuratie uitbreiden:
|
|
|
|
```js title="tailwind.config.js"
|
|
module.exports = {
|
|
theme: {
|
|
extend: {
|
|
data: {
|
|
open: 'state="open"',
|
|
closed: 'state="closed"',
|
|
active: 'state="active"',
|
|
}
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
Nu kun je een shorthand gebruiken:
|
|
|
|
```tsx
|
|
<Dialog className="data-open:opacity-100 data-closed:opacity-0" />
|
|
```
|
|
|
|
### Integratie met Radix UI
|
|
|
|
Dit patroon wordt veel gebruikt door [Radix UI](https://www.radix-ui.com/), dat automatisch data-attributen op zijn primitives toepast:
|
|
|
|
```tsx
|
|
import * as Dialog from '@radix-ui/react-dialog';
|
|
|
|
<Dialog.Root>
|
|
<Dialog.Trigger />
|
|
<Dialog.Portal>
|
|
{/* Radix automatically adds data-state="open" | "closed" */}
|
|
<Dialog.Overlay className="data-[state=open]:animate-in data-[state=closed]:animate-out" />
|
|
<Dialog.Content className="data-[state=open]:fade-in data-[state=closed]:fade-out" />
|
|
</Dialog.Portal>
|
|
</Dialog.Root>
|
|
```
|
|
|
|
Andere data-attributen die Radix levert zijn onder meer:
|
|
- `data-state` - open/gesloten, actief/inactief, aan/uit
|
|
- `data-side` - top/right/bottom/left (voor gepositioneerde elementen)
|
|
- `data-align` - start/center/end (voor gepositioneerde elementen)
|
|
- `data-orientation` - horizontal/vertical
|
|
- `data-disabled` - aanwezig wanneer uitgeschakeld
|
|
- `data-placeholder` - aanwezig bij het tonen van een placeholder
|
|
|
|
## Componentidentificatie met data-slot
|
|
|
|
Terwijl `data-state` visuele staten bijhoudt, identificeert `data-slot` componenttypes binnen een compositie. Dit patroon, populair gemaakt door [shadcn/ui](https://ui.shadcn.com/), stelt parent-componenten in staat om specifieke child-componenten te targeten en te stylen zonder te vertrouwen op kwetsbare class-namen of elementselectoren.
|
|
|
|
### Het probleem met het targeten van onderliggende componenten
|
|
|
|
Traditionele benaderingen om onderliggende componenten te stylen hebben aanzienlijke beperkingen:
|
|
|
|
```tsx
|
|
// Relies on element types - breaks if implementation changes
|
|
<form className="[&_input]:rounded-lg [&_button]:mt-4" />
|
|
|
|
// Relies on class names - breaks if classes change
|
|
<form className="[&_.text-input]:rounded-lg" />
|
|
|
|
// Requires passing classes through props - verbose
|
|
<form>
|
|
<input className={inputClasses} />
|
|
<button className={buttonClasses} />
|
|
</form>
|
|
```
|
|
|
|
### De oplossing: data-slot-attributen
|
|
|
|
Gebruik `data-slot` om componenten stabiele identificatoren te geven die door parents gericht kunnen worden:
|
|
|
|
```tsx title="field-set.tsx"
|
|
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
|
|
return (
|
|
<fieldset
|
|
data-slot="field-set"
|
|
className={cn(
|
|
"flex flex-col gap-6",
|
|
// Target specific child slots
|
|
"has-[>[data-slot=checkbox-group]]:gap-3",
|
|
"has-[>[data-slot=radio-group]]:gap-3",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
```
|
|
|
|
```tsx title="checkbox-group.tsx"
|
|
function CheckboxGroup({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="checkbox-group"
|
|
className={cn("flex flex-col gap-2", className)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
```
|
|
|
|
### Voordelen van data-slot
|
|
|
|
1. **Stabiele identificatoren** - Breekt niet wanneer implementatiedetails veranderen
|
|
2. **Semantisch targeten** - Target op basis van componentdoel, niet structuur
|
|
3. **Encapsulatie** - Interne classes blijven privé
|
|
4. **Compositie** - Werkt met willekeurige nesting en compositie
|
|
5. **Type-safe** - Kan gevalideerd en gedocumenteerd worden
|
|
|
|
### Gebruik van `has-[]` voor ouderbewuste styling
|
|
|
|
Tailwind's `has-[]` selector gecombineerd met `data-slot` creëert krachtige ouderbewuste styling:
|
|
|
|
```tsx title="form.tsx"
|
|
function Form({ className, ...props }: React.ComponentProps<"form">) {
|
|
return (
|
|
<form
|
|
data-slot="form"
|
|
className={cn(
|
|
"space-y-4",
|
|
// Adjust spacing when specific slots are present
|
|
"has-[>[data-slot=form-section]]:space-y-6",
|
|
"has-[>[data-slot=inline-fields]]:space-y-2",
|
|
// Style based on slot states
|
|
"has-[[data-slot=submit-button][data-loading=true]]:opacity-50",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
```
|
|
|
|
### Gebruik van `[&_]` voor het targeten van afstammelingen
|
|
|
|
Voor diepere nesting, gebruik het `[&_selector]`-patroon om elk afstammelingselement te targeten:
|
|
|
|
```tsx title="card.tsx"
|
|
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
|
return (
|
|
<div
|
|
data-slot="card"
|
|
className={cn(
|
|
"rounded-lg border p-4",
|
|
// Target any descendant with data-slot
|
|
"[&_[data-slot=card-header]]:mb-4",
|
|
"[&_[data-slot=card-title]]:text-lg [&_[data-slot=card-title]]:font-semibold",
|
|
"[&_[data-slot=card-description]]:text-sm [&_[data-slot=card-description]]:text-muted-foreground",
|
|
"[&_[data-slot=card-footer]]:mt-4 [&_[data-slot=card-footer]]:border-t [&_[data-slot=card-footer]]:pt-4",
|
|
className
|
|
)}
|
|
{...props}
|
|
/>
|
|
);
|
|
}
|
|
```
|
|
|
|
### Globale CSS met data-slot
|
|
|
|
Data-slots werken uitstekend met globale CSS voor thema-brede consistentie:
|
|
|
|
```css title="globals.css"
|
|
/* Style all buttons within forms */
|
|
[data-slot="form"] [data-slot="button"] {
|
|
@apply w-full sm:w-auto;
|
|
}
|
|
|
|
/* Style submit buttons specifically */
|
|
[data-slot="form"] [data-slot="submit-button"] {
|
|
@apply bg-primary text-primary-foreground;
|
|
}
|
|
|
|
/* Adjust inputs within inline layouts */
|
|
[data-slot="inline-fields"] [data-slot="input"] {
|
|
@apply flex-1;
|
|
}
|
|
|
|
/* Style based on state combinations */
|
|
[data-slot="dialog"][data-state="open"] [data-slot="dialog-content"] {
|
|
@apply animate-in fade-in;
|
|
}
|
|
```
|
|
|
|
### Naamgevingsconventies
|
|
|
|
Volg deze conventies voor consistente `data-slot`-naamgeving:
|
|
|
|
1. **Gebruik kebab-case** - `data-slot="form-field"` in plaats van `data-slot="formField"`
|
|
2. **Wees specifiek** - `data-slot="submit-button"` in plaats van `data-slot="button"`
|
|
3. **Komponenteer doel laten weerspiegelen** - Naam weerspiegelt wat het doet, niet hoe het eruitziet
|
|
4. **Vermijd implementatiedetails** - `data-slot="user-avatar"` in plaats van `data-slot="rounded-image"`
|
|
|
|
```tsx
|
|
// Good examples
|
|
data-slot="search-input"
|
|
data-slot="navigation-menu"
|
|
data-slot="error-message"
|
|
data-slot="submit-button"
|
|
data-slot="card-header"
|
|
|
|
// Avoid
|
|
data-slot="input" // Too generic
|
|
data-slot="blueButton" // Includes styling
|
|
data-slot="div-wrapper" // Implementation detail
|
|
data-slot="mainContent" // Use camelCase
|
|
```
|
|
|
|
## Wanneer data-attributen gebruiken vs props
|
|
|
|
Begrijpen wanneer je elk patroon moet gebruiken is essentieel voor een nette API:
|
|
|
|
### Gebruikssituaties voor `data-state`
|
|
- **Visuele staten** - open/gesloten, actief/inactief, loading, enz.
|
|
- **Lay-outstaten** - oriëntatie, zijde, uitlijning
|
|
- **Interactiestaten** - hover, focus, disabled (wanneer je kinderen wilt stylen)
|
|
|
|
### Gebruikssituaties voor `data-slot`
|
|
- **Componentidentificatie** - Stabiele identificatoren om te targeten
|
|
- **Compositiestructuren** - Parent-child-relaties
|
|
- **Globale styling** - Thema-brede componentstyling
|
|
- **Variant-onafhankelijk targeten** - Target elke variant van een component
|
|
|
|
### Gebruikssituaties voor `props`
|
|
- **Varianten** - Verschillende visuele ontwerpen (primary, secondary, destructive)
|
|
- **Maten** - sm, md, lg
|
|
- **Gedragsconfiguratie** - controlled/uncontrolled, standaardwaarden
|
|
- **Event handlers** - onClick, onChange, enz.
|
|
|
|
### Gecombineerde aanpak
|
|
|
|
Een goed ontworpen component gebruikt alle drie patronen op de juiste manier:
|
|
|
|
```tsx title="button.tsx"
|
|
type ButtonProps = {
|
|
variant?: 'primary' | 'secondary' | 'destructive';
|
|
size?: 'sm' | 'md' | 'lg';
|
|
loading?: boolean;
|
|
disabled?: boolean;
|
|
onClick?: () => void;
|
|
className?: string;
|
|
};
|
|
|
|
const Button = ({
|
|
variant = 'primary',
|
|
size = 'md',
|
|
loading,
|
|
disabled,
|
|
className,
|
|
...props
|
|
}: ButtonProps) => {
|
|
return (
|
|
<button
|
|
// Slot for targeting
|
|
data-slot="button"
|
|
// State for conditional styling
|
|
data-loading={loading}
|
|
data-disabled={disabled}
|
|
className={cn(
|
|
// Variant styles via props
|
|
buttonVariants({ variant, size }),
|
|
// Additional state styling allowed via className
|
|
className
|
|
)}
|
|
disabled={disabled}
|
|
{...props}
|
|
/>
|
|
);
|
|
};
|
|
```
|
|
|
|
Nu kan de Button op meerdere manieren worden gebruikt en gestyled:
|
|
|
|
```tsx
|
|
// Basic usage with variants
|
|
<Button variant="primary" size="lg">Submit</Button>
|
|
|
|
// Parent targeting via data-slot
|
|
<form className="[&_[data-slot=button]]:w-full">
|
|
<Button>Submit</Button>
|
|
</form>
|
|
|
|
// State-based styling via data-state
|
|
<Button
|
|
loading={isLoading}
|
|
className="data-[loading=true]:opacity-50"
|
|
>
|
|
Submit
|
|
</Button>
|
|
|
|
// Global CSS can target any button
|
|
// [data-slot="button"][data-loading="true"] { ... }
|
|
```
|
|
|
|
Data-attributen bieden een robuuste basis voor het stylen van moderne componentbibliotheken. Door `data-state` te gebruiken voor visuele staten en `data-slot` voor componentidentificatie creëer je een flexibele, onderhoudbare API die schaalt van eenvoudige componenten tot complexe designsystemen. |