# Introduction URL: https://emotion-variants.org/docs/introduction/ `emotion-variants` is a thin layer on top of [`@emotion/react`](https://emotion.sh/) that lets you define every visual permutation of a component — base styles, variants, compound combinations, and defaults — in a **single configuration object**, with full TypeScript inference. ## The problem [#the-problem] A real-world button has multiple visual axes: size, color, fill style, state. With vanilla Emotion, those axes pull your styles into multiple places — a lookup table here, a conditional spread there, hand-written prop types somewhere else. ```tsx // @emotion/react only import { css } from '@emotion/react'; // 1. Lookup tables, separate from the component const sizeStyles = { small: { padding: '8px 16px', fontSize: 12, }, medium: { padding: '10px 20px', fontSize: 14, }, large: { padding: '12px 24px', fontSize: 16, }, }; const colorStyles = { primary: { background: 'blue', color: 'white', }, danger: { background: 'red', color: 'white', }, }; // 2. Prop types maintained by hand type ButtonProps = { size?: 'small' | 'medium' | 'large'; color?: 'primary' | 'danger'; }; // 3. Component owns: defaults, composition, and compound logic function Button({ size = 'medium', color = 'primary' }: ButtonProps) { return ( ); } ``` Adding one new `size` value means touching the lookup table, the prop type union, and — if it participates in a compound rule — the component itself. ## The solution [#the-solution] `emotion-variants` collapses all of that into a single configuration object. ```tsx // With emotion-variants import { ev, type VariantProps } from 'emotion-variants'; const button = ev({ base: { borderRadius: 8, cursor: 'pointer', }, variants: { size: { small: { padding: '8px 16px', fontSize: 12, }, medium: { padding: '10px 20px', fontSize: 14, }, large: { padding: '12px 24px', fontSize: 16, }, }, color: { primary: { background: 'blue', color: 'white', }, danger: { background: 'red', color: 'white', }, }, }, compoundVariants: [ { variants: { size: 'large', color: 'primary', }, style: { fontWeight: 'bold', }, }, ], defaultVariants: { size: 'medium', color: 'primary', }, }); type ButtonProps = VariantProps; function Button({ size, color }: ButtonProps) { return ; } ``` Adding a new `size` value? One line, one place: `variants.size`. The prop types update automatically. ## Side-by-side [#side-by-side] | | Without `emotion-variants` | With `emotion-variants` | |---|---|---| | Style definition | Lookup tables, scattered files | Single config object | | Variant prop types | Hand-written union | Inferred from config | | Compound rules | Inline conditional in component | `compoundVariants` array | | Default values | Function-argument defaults | `defaultVariants` | | Add a new variant value | Touch lookup + type + component | Touch `variants` | | Generated class names | Not exposed | `button.classNames` | | New consumer reading the code | Reads 3 files to understand styling | Reads 1 object | ## When not to use it [#when-not-to-use-it] - If your component has zero or one variant, plain `css()` is simpler. - If you need runtime theming with arbitrary CSS variables resolved per render, `emotion-variants` works but you may want to lean more on Emotion's `theme` directly. ## Next steps [#next-steps] - [Install](./installation.mdx) the package and peer dependencies. - Walk through [Quick Start](./quick-start.mdx) to build your first component. - Read [Variants](./variants.mdx) to understand `base` and `variants` in depth. # Installation URL: https://emotion-variants.org/docs/installation/ ## Requirements [#requirements] - **React** 16.14 or newer — the automatic JSX runtime (`react/jsx-runtime`) landed in 16.14 - **`@emotion/react`** 11.x - **`@emotion/css`** 11.x ## Install [#install] ```sh tab="npm" npm install emotion-variants @emotion/react @emotion/css ``` ```sh tab="pnpm" pnpm add emotion-variants @emotion/react @emotion/css ``` ```sh tab="yarn" yarn add emotion-variants @emotion/react @emotion/css ``` ```sh tab="bun" bun add emotion-variants @emotion/react @emotion/css ``` Both Emotion packages are peer dependencies and must be installed alongside `emotion-variants`. `@emotion/react` serializes your styles for the `css` prop; `@emotion/css` backs [`className()` and `classNames`](./ev.mdx#classname). `@emotion/css` is imported unconditionally, so it is required even if you only ever use the `css` prop. ## Enable the `css` prop [#enable-the-css-prop] `emotion-variants` returns values you pass to Emotion's `css` prop. Make sure your project is set up to use it. The simplest setup points the automatic JSX runtime at Emotion: ```json // tsconfig.json { "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "@emotion/react" } } ``` Both options are required. `jsxImportSource` has no effect under `"jsx": "react"` — that is the classic transform, which calls `React.createElement` and never consults an import source. Or per file, for a project that cannot switch globally: ```tsx /** @jsxImportSource @emotion/react */ ``` The pragma needs the automatic runtime too, so it must be the first thing in the file and the file must be compiled with `react-jsx`. On React older than 16.14, use [Emotion's Babel plugin](https://emotion.sh/docs/css-prop#babel-plugin) with the classic transform instead. See [Emotion's installation guide](https://emotion.sh/docs/css-prop) for other setups (Next.js, Vite, etc.). ## Verify [#verify] Create a tiny component and render it. If TypeScript autocompletes `size` inside `button({ ... })`, you're good to go. ```tsx import type { ComponentPropsWithoutRef } from 'react'; import { ev, type VariantProps } from 'emotion-variants'; const button = ev({ base: { padding: '8px 16px', }, variants: { size: { sm: { fontSize: 12, }, lg: { fontSize: 16, }, }, }, }); type ButtonProps = ComponentPropsWithoutRef<'button'> & VariantProps; export function Button({ size, ...rest }: ButtonProps) { return ``` Because `defaultVariants` is set, `` renders as `medium` + `primary`. ## 3. Derive props from the variant function [#3-derive-props-from-the-variant-function] You don't have to hand-roll the prop types. Pull them out of the variant function with the `VariantProps` type: ```tsx import { ev, type VariantProps } from 'emotion-variants'; const button = ev({ /* ... */ }); type ButtonVariants = VariantProps; type ButtonProps = ComponentPropsWithoutRef<'button'> & ButtonVariants; ``` This keeps your component's prop types and styles in sync. Add a new variant value and `ButtonProps` updates automatically. See [TypeScript](./typescript.mdx) for more patterns, such as forwarding a ref. ## What's next [#whats-next] - [Variants](./variants.mdx) — `base` and `variants` in depth. - [API Reference](./ev.mdx) — exhaustive `ev()` documentation. - [Compound Variants](./compound-variants.mdx) — styles that apply only to a combination. # Variants URL: https://emotion-variants.org/docs/variants/ `ev()` accepts a single configuration object. This page covers `base` and `variants`. [`defaultVariants`](./default-variants.mdx), [`compoundVariants`](./compound-variants.mdx), and [`slots`](./slots.mdx) each have their own page. ```ts ev({ base, // styles applied to all variants variants, // axis × value → styles compoundVariants, // styles applied when multiple axes match defaultVariants, // fallback values when the consumer omits a prop }); ``` ## `base` [#base] `base` styles are applied to every call of the variant function. Use it for properties that don't depend on any variant. ```ts const button = ev({ base: { padding: '10px 20px', borderRadius: '8px', border: 'none', cursor: 'pointer', }, }); button(); // applies only base styles ``` `base` accepts a single `CSSObject` and supports Emotion's full syntax — nested selectors, pseudo-classes, media queries, keyframes via `@keyframes`, etc. ```ts const button = ev({ base: { transition: 'transform 0.2s ease', '&:hover': { transform: 'translateY(-2px)', }, '&:disabled': { opacity: 0.6, cursor: 'not-allowed', }, }, }); ``` ## `variants` [#variants] `variants` is a record of axes. Each axis maps from a value to a `CSSObject`. ```tsx const button = ev({ base: { border: '1px solid transparent', borderRadius: 8, cursor: 'pointer', fontWeight: 600, transition: 'all 0.2s ease', }, variants: { variant: { filled: { background: 'var(--button-color)', color: 'white', }, outlined: { background: 'transparent', borderColor: 'var(--button-color)', color: 'var(--button-color)', }, text: { background: 'transparent', color: 'var(--button-color)', }, }, size: { small: { padding: '8px 16px', fontSize: 12, }, medium: { padding: '10px 20px', fontSize: 14, }, large: { padding: '12px 24px', fontSize: 16, }, }, color: { primary: { '--button-color': '#d36ac2', }, secondary: { '--button-color': '#475569', }, }, }, }); ``` Variant values can be **strings**, **numbers**, or **booleans**: ```ts const panel = ev({ variants: { color: { red: { color: 'red', }, blue: { color: 'blue', }, }, level: { 1: { zIndex: 1, }, 2: { zIndex: 2, }, }, outlined: { true: { border: '1px solid', }, false: { border: 'none', }, }, }, }); panel({ color: 'red', level: 2, outlined: true }); ``` Boolean variant values use the literal string keys `'true'` and `'false'` in the configuration, but you pass actual booleans (`true` / `false`) when calling the function. ## Style precedence [#style-precedence] For a given call, styles are appended in this order (later wins on CSS conflicts): 1. `base` 2. Each matching simple `variants` entry, in the order keys appear in `variants` 3. Each matching `compoundVariants` entry, in array order # Default Variants URL: https://emotion-variants.org/docs/default-variants/ `defaultVariants` lets consumers omit props and still get a styled component. This page covers when to use them, common pitfalls, and patterns for sensible defaults. ## `defaultVariants` [#defaultvariants] `defaultVariants` sets fallback values used when the consumer omits a variant. ```tsx const button = ev({ base: { border: '1px solid transparent', borderRadius: 8, cursor: 'pointer', fontWeight: 600, transition: 'all 0.2s ease', }, variants: { variant: { filled: { background: 'var(--button-color)', color: 'white', }, outlined: { background: 'transparent', borderColor: 'var(--button-color)', color: 'var(--button-color)', }, text: { background: 'transparent', color: 'var(--button-color)', }, }, size: { small: { padding: '8px 16px', fontSize: 12, }, medium: { padding: '10px 20px', fontSize: 14, }, large: { padding: '12px 24px', fontSize: 16, }, }, color: { primary: { '--button-color': '#d36ac2', }, secondary: { '--button-color': '#475569', }, }, }, defaultVariants: { variant: 'filled', size: 'medium', color: 'primary', }, }); ``` ## Set defaults that match the most common case [#set-defaults-that-match-the-most-common-case] If 80% of `; } ``` ```ts button({ size: undefined }); // identical to button() — medium primary ``` `null` falls back the same way at runtime, but `EvVariants` does not include it — under `strictNullChecks` a nullable value has to be normalized to `undefined` before it is passed. This means you don't need a prop default (`{ size = 'medium' }`) on top of `defaultVariants`. Pick one place to declare the default, and `defaultVariants` is the one that also covers direct `button()` calls from outside the component. `false` and `0` are valid variant values, so they are used as-is rather than falling back. ```ts const badge = ev({ variants: { outlined: { true: { border: '1px solid', }, false: { border: 'none', }, }, }, defaultVariants: { outlined: true, }, }); badge({ outlined: false }); // border: none, not the default `true` style ``` ## Defaults for boolean variants [#defaults-for-boolean-variants] Use literal `true` / `false`, not the string keys: ```ts const chip = ev({ variants: { outlined: { true: { border: '1px solid', }, false: { border: 'none', }, }, }, defaultVariants: { outlined: false, }, }); chip(); // applies the `false` style ``` ## Defaults play well with compound variants [#defaults-play-well-with-compound-variants] Defaults seed the variant values used to evaluate compound matches. ```ts const button = ev({ variants: { size: { small: {}, large: {}, }, color: { primary: {}, danger: {}, }, }, compoundVariants: [ { variants: { size: 'large', color: 'primary', }, style: { fontWeight: 'bold', }, }, ], defaultVariants: { size: 'large', color: 'primary', }, }); button(); // bold because defaults satisfy the compound condition ``` ## See also [#see-also] - [Compound Variants](./compound-variants.mdx) # Compound Variants URL: https://emotion-variants.org/docs/compound-variants/ Compound variants apply styles only when the variant values you list all match. They're the answer to "I want this style only when `variant: 'outlined'` *and* `color: 'danger'`." Listing a single axis is allowed too — it then behaves like a variant style that is applied after all the others. ## `compoundVariants` [#compoundvariants] A compound variant applies styles only when **multiple axes** match specific values. Useful for "X looks different when it's also Y" patterns. ```tsx const button = ev({ base: { border: '1px solid transparent', borderRadius: 8, cursor: 'pointer', fontWeight: 600, transition: 'all 0.2s ease', }, variants: { variant: { filled: { background: 'var(--button-color)', color: 'white', }, outlined: { background: 'transparent', borderColor: 'var(--button-color)', color: 'var(--button-color)', }, text: { background: 'transparent', color: 'var(--button-color)', }, }, size: { small: { padding: '8px 16px', fontSize: 12, }, medium: { padding: '10px 20px', fontSize: 14, }, large: { padding: '12px 24px', fontSize: 16, }, }, color: { primary: { '--button-color': '#d36ac2', }, secondary: { '--button-color': '#475569', }, }, }, compoundVariants: [ { variants: { variant: 'filled', size: 'large', color: 'primary', }, style: { boxShadow: '0 4px 12px rgba(211, 106, 194, 0.4)', }, }, ], defaultVariants: { variant: 'filled', size: 'medium', color: 'primary', }, }); ``` Compound variants are evaluated in array order and stacked **after** the matching simple variants, so they can safely override. ## When to reach for them [#when-to-reach-for-them] Use a compound variant when: - A style depends on two or more axes simultaneously. - Expressing the style as a single-axis variant would force you to invent a new axis or duplicate values. - Conditional CSS inside the component (`size === 'lg' && color === 'primary' && ...`) is creeping in. If a style depends on only one axis, put it directly in `variants` — compound variants are for the cross-product. ## Pattern: filled / outlined / text × color [#pattern-filled--outlined--text--color] A common design system pattern: the same set of colors styled three ways. ```ts import { ev } from 'emotion-variants'; const button = ev({ base: { padding: '8px 16px', borderRadius: 8, cursor: 'pointer', border: 'none', }, variants: { variant: { filled: {}, outlined: { background: 'transparent', border: '2px solid currentColor', }, text: { background: 'transparent', }, }, color: { primary: {}, danger: {}, }, }, compoundVariants: [ // Filled { variants: { variant: 'filled', color: 'primary', }, style: { background: '#d36ac2', color: 'white', }, }, { variants: { variant: 'filled', color: 'danger', }, style: { background: '#dc2626', color: 'white', }, }, // Outlined { variants: { variant: 'outlined', color: 'primary', }, style: { color: '#d36ac2', }, }, { variants: { variant: 'outlined', color: 'danger', }, style: { color: '#dc2626', }, }, // Text { variants: { variant: 'text', color: 'primary', }, style: { color: '#d36ac2', }, }, { variants: { variant: 'text', color: 'danger', }, style: { color: '#dc2626', }, }, ], defaultVariants: { variant: 'filled', color: 'primary', }, }); ``` The `color` variant has empty objects in `variants` because the styling only makes sense **in combination** with `variant`. Compound variants carry the actual values. ## Pattern: size × density override [#pattern-size--density-override] Sometimes a compound variant tweaks a base property only at a specific intersection. ```ts const card = ev({ base: { padding: 16, borderRadius: 12, }, variants: { size: { sm: { padding: 12, }, md: { padding: 16, }, lg: { padding: 24, }, }, density: { comfortable: {}, compact: {}, }, }, compoundVariants: [ { variants: { size: 'lg', density: 'compact', }, style: { padding: 16, }, }, ], }); ``` Only the `lg + compact` corner overrides the size's natural padding. ## Matching several values [#matching-several-values] A condition can be an array. It matches when the variant has **any** of the listed values, so one entry covers what would otherwise be a copy per value. ```ts const button = ev({ variants: { variant: { filled: {}, outlined: {}, text: {}, }, color: { primary: {}, danger: {}, }, }, compoundVariants: [ { variants: { variant: ['outlined', 'text'], color: 'danger', }, style: { color: 'crimson', }, }, ], }); button({ variant: 'outlined', color: 'danger' }); // includes the compound style button({ variant: 'text', color: 'danger' }); // includes it too button({ variant: 'filled', color: 'danger' }); // does NOT include it ``` Axes are still combined with AND. Every listed axis has to match; an array only widens what counts as a match for its own axis. An empty array never matches. ## Order matters [#order-matters] Compound variants are appended **after** simple variants for each call, in the order they appear in the array. If two compound variants both match and set the same property, the later one wins. ```ts compoundVariants: [ { variants: { size: 'lg', }, style: { fontWeight: 600, }, }, { variants: { size: 'lg', color: 'primary', }, style: { fontWeight: 700, // overrides the entry above }, }, ], ``` You can include compound variants that match only a **single** axis. They behave like normal variants but are useful when you want to keep all "conditional" rules in one place. ## See also [#see-also] - [Default Variants](./default-variants.mdx) # Slots URL: https://emotion-variants.org/docs/slots/ A component is rarely a single element. A card has a root, a title, and a footer, and a variant such as `size` usually restyles several of them at once. `slots` lets one `ev()` call style every part, so the parts share the same variants and can't drift apart. ## Declare the parts [#declare-the-parts] Use `slots` instead of `base`. Each key names a part of the component and holds its base styles. ```ts import { ev } from 'emotion-variants'; const card = ev({ slots: { root: { borderRadius: 12, padding: 16, }, title: { fontWeight: 600, }, footer: { display: 'flex', gap: 8, }, }, }); ``` Calling `card()` now returns one style function per slot. Call each one where its element is rendered: ```tsx import type { ComponentPropsWithoutRef, ReactNode } from 'react'; type CardProps = ComponentPropsWithoutRef<'section'> & { heading: ReactNode; }; function Card({ heading, children, ...rest }: CardProps) { const { root, title, footer } = card(); return (

{heading}

{children}
); } ``` A slot is a function, not a style. Write `css={root()}`. Emotion calls a function passed to `css` with the theme, so `css={root}` reads the theme object as the slot's variants. ## Variants per slot [#variants-per-slot] With `slots`, a variant value maps slot names to styles. A value only lists the slots it changes. ```tsx const card = ev({ slots: { root: { display: 'flex', flexDirection: 'column', gap: 6, width: 320, border: '1px solid #e4e4e7', borderRadius: 12, background: 'white', color: '#09090b', boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)', }, title: { fontWeight: 600, }, footer: { display: 'flex', gap: 8, fontSize: 14, color: '#71717a', }, }, variants: { size: { small: { root: { padding: 16, }, title: { fontSize: 16, }, }, large: { root: { padding: 24, }, title: { fontSize: 18, }, }, }, tone: { neutral: {}, accent: { title: { color: '#d36ac2', }, }, }, }, defaultVariants: { size: 'small', tone: 'neutral', }, }); const { root, title, footer } = card({ size: 'large', tone: 'accent', });

Weekly report

Updated 2 hours ago
```
One call resolves the variants for every slot. `root()` gets the large padding, `title()` gets the large font size and the accent color, and `footer()` gets only its base styles because no variant mentions it. ## Override a variant for one slot [#override-a-variant-for-one-slot] Each slot function accepts the same variant props as the call. A slot prop wins over the call's props, which win over `defaultVariants`. ```tsx const { root, title } = card({ size: 'large', }); root(); // large title({ size: 'small', }); // small, for the title only ``` As everywhere else, `undefined` falls through to the next level, so forwarding an optional prop to a slot is safe. ## Compound variants [#compound-variants] `compoundVariants` works the same way, except that `style` is keyed by slot. ```ts compoundVariants: [ { variants: { size: 'large', tone: 'accent', }, style: { title: { textTransform: 'uppercase', }, }, }, ], ``` Compounds are matched per slot, against the values that slot resolved to. Overriding a variant on one slot can therefore switch a compound on or off for that slot alone: ```ts const { title } = card({ tone: 'accent', }); title(); // small + accent: no compound title({ size: 'large', }); // large + accent: uppercase ``` ## The same style on several slots [#the-same-style-on-several-slots] `compoundSlots` applies one style to a list of slots. It saves repeating the style under each slot name. ```ts compoundSlots: [ { slots: ['title', 'footer'], style: { paddingInline: 4, }, }, { slots: ['root', 'footer'], variants: { size: 'large', }, style: { gap: 16, }, }, ], ``` `variants` is optional. Without it the entry always applies; with it the entry follows the same matching rules as `compoundVariants`, array conditions included. ## Order [#order] For each slot, styles are appended in this order, and later entries win on CSS conflicts: 1. The slot's base styles from `slots` 2. Matching `variants` entries, in the order the axes were declared 3. Matching `compoundVariants` entries, in array order 4. Matching `compoundSlots` entries, in array order ## Class names [#class-names] `className()` returns one class name per slot. ```tsx const classNames = card.className({ size: 'large', });

Title

; ``` There is no `classNames` lookup table when `slots` is declared. ## Rules [#rules] - `base` and `slots` cannot be combined. Put the styles in a slot, commonly one named `root`. - A variant value, a compound `style`, and a `compoundSlots` entry may only name declared slots. Anything else is a type error, which catches typos. - Selectors such as `'&:hover'` go inside a slot's style, not next to the slot names. - `compoundSlots` requires `slots`. ## Props [#props] [`VariantProps`](./typescript.mdx) works on a slot function too, and gives you the variant props shared by all slots. ```ts import type { VariantProps } from 'emotion-variants'; type CardVariants = VariantProps; // { size?: 'small' | 'large'; tone?: 'neutral' | 'accent' } ``` ## See also [#see-also] - [Compound Variants](./compound-variants.mdx) - [API Reference → slots](./ev.mdx#slots) # Overrides URL: https://emotion-variants.org/docs/overrides/ Sometimes one instance needs a style that doesn't belong on any axis — a button that stretches full width in a form, a card with a one-off margin. `ev()` has no `class` or `css` escape hatch in its config, so overrides happen at the call site. ## Usage [#usage] ### Append styles to the `css` prop [#append-styles-to-the-css-prop] The variant function returns `SerializedStyles[]`, and Emotion's `css` prop accepts arrays. Put your extra styles **after** the variant result and they win. ```tsx ``` Emotion flattens nested arrays, so spreading is optional. Both forms behave identically: ```tsx ; ``` Order is the mechanism — Emotion concatenates in array order, and among declarations of **equal specificity** the last one wins. Put the override first and it loses: ```tsx // ✗ `width` is overwritten by base/variant styles ; // ✓ the override is last ; ``` ### Accept overrides as a prop [#accept-overrides-as-a-prop] Give the component a prop for extra styles and append it in the same position. Callers then override without knowing how the styles are built. ```tsx import type { Interpolation, Theme } from '@emotion/react'; import type { ComponentPropsWithoutRef } from 'react'; import type { VariantProps } from 'emotion-variants'; type ButtonProps = ComponentPropsWithoutRef<'button'> & VariantProps & { styleOverride?: Interpolation; }; function Button({ size, color, styleOverride, ...rest }: ButtonProps) { return ``` Do not name that prop `css`. Emotion's JSX runtime consumes `css` at the call site and hands the component a `className` instead, so a `css` prop never reaches `Button` and the override is silently dropped. Any other name is forwarded untouched. ### Overriding on `className` surfaces [#overriding-on-classname-surfaces] [`className()`](./ev.mdx#classname) returns a single class, so appending another class does **not** reliably win — both classes have the same specificity and the winner is whichever Emotion inserted later. ```tsx // ✗ ordering is not guaranteed ; ``` Compose the styles instead of the classes, then turn the result into one class with `@emotion/css`: ```tsx import { css as cssClassName } from '@emotion/css'; const full = cssClassName(button({ size: 'large' }), { width: '100%' }); ; ``` Order only decides ties. A flat declaration never beats a more specific selector, so `{ width: '100%' }` appended after a variant does not win while that variant's `&:hover` rule applies. Match the selector you are overriding: ```tsx ; ``` ## When to add a variant instead [#when-to-add-a-variant-instead] Reach for an override when the style belongs to **one call site**. If you write the same override twice, it is an axis: ```ts // Two call sites both needed full width — make it a variant. const button = ev({ variants: { size: { small: {}, large: {}, }, fullWidth: { true: { width: '100%', }, false: {}, }, }, defaultVariants: { fullWidth: false, }, }); ``` That keeps the override path for genuine one-offs and gives the repeated case a name, a type, and a class name. ## See also [#see-also] - [Variants → Style precedence](./variants.mdx#style-precedence) - [Compound Variants](./compound-variants.mdx) — styles for a combination, not a single instance # Extend URL: https://emotion-variants.org/docs/extending/ Some components are another component plus a little more: an icon button is a button with a fixed width, a danger card is a card with one more tone. `extend` builds one `ev()` result on top of another, so the shared styles and variants are declared once. ## Build on another function [#build-on-another-function] Pass an `ev()` result as `extend`. The new function inherits everything the parent declared. ```tsx import { ev } from 'emotion-variants'; const button = ev({ base: { border: '1px solid transparent', borderRadius: 8, cursor: 'pointer', fontWeight: 600, transition: 'all 0.2s ease', }, variants: { variant: { filled: { background: 'var(--button-color)', color: 'white', }, outlined: { background: 'transparent', borderColor: 'var(--button-color)', color: 'var(--button-color)', }, text: { background: 'transparent', color: 'var(--button-color)', }, }, size: { small: { padding: '8px 16px', fontSize: 12, }, medium: { padding: '10px 20px', fontSize: 14, }, large: { padding: '12px 24px', fontSize: 16, }, }, color: { primary: { '--button-color': '#d36ac2', }, secondary: { '--button-color': '#475569', }, }, }, defaultVariants: { variant: 'filled', size: 'medium', color: 'primary', }, }); const iconButton = ev({ extend: button, base: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 44, height: 44, }, }); ``` `iconButton` accepts `variant`, `size`, and `color`, applies the parent's defaults, and adds its own `base` after the parent's. `button` itself is not changed. ## Add values and axes [#add-values-and-axes] A child can add values to an inherited axis, add styles to an inherited value, and declare new axes. ```ts const iconButton = ev({ extend: button, variants: { size: { large: { width: 48, }, huge: { fontSize: 24, }, }, round: { true: { borderRadius: '50%', }, }, }, }); iconButton.variants(); // ['variant', 'size', 'color', 'round'] ``` - `size: 'small'` is inherited as it is. - `size: 'large'` gets the parent's font size, then the child's width. - `size: 'huge'` and the `round` axis exist only on `iconButton`. Inherited axes keep their position, and new axes come after them. ## Defaults and compound variants [#defaults-and-compound-variants] `defaultVariants` are merged per axis, and the child's value wins. The child's `compoundVariants` and `defaultVariants` can refer to inherited axes and values. ```ts const iconButton = ev({ extend: button, variants: { round: { true: { borderRadius: '50%', }, }, }, compoundVariants: [ { variants: { variant: 'outlined', round: true, }, style: { borderWidth: 2, }, }, ], defaultVariants: { size: 'large', }, }); ``` The parent's compound variants are inherited too, and they are matched against the values the child resolved. ## Order [#order] At every step, the parent's styles come before the child's. Later entries win on CSS conflicts. 1. `base`, parent then child 2. Matching `variants` entries, axis by axis; for each value, parent then child 3. Matching `compoundVariants` entries, parent then child Every compound variant comes after every variant style. So a parent's compound variant still wins over a style the child declares for the same variant value. To override it, add a compound variant with the same condition to the child. The chain can be as long as you like. Extending `iconButton` again puts `button` first, `iconButton` second, and the new config last. ## With slots [#with-slots] A [slots](./slots.mdx) function extends another slots function. The child can add slots, and add styles to inherited slots. ```ts const card = ev({ slots: { root: { padding: 16, }, title: { fontWeight: 600, }, }, }); const mediaCard = ev({ extend: card, slots: { root: { overflow: 'hidden', }, footer: { display: 'flex', }, }, }); const { root, title, footer } = mediaCard(); ``` A child that declares no `slots` keeps the parent's slots, and its variant values are still keyed by slot name. ## Class names [#class-names] `className()` includes the inherited styles. In `classNames`, each entry merges the parent's and the child's styles for that key, and a value the child did not touch keeps the parent's class name. ## Rules [#rules] - `extend` takes a single `ev()` result. Anything else throws when `ev()` runs. If the value did come from `ev()`, two copies of `emotion-variants` are probably installed. - A config with `slots` can only extend one with `slots`. Extending a plain function throws, and is a type error. - When the parent has `slots`, the child cannot use `base`. Put the styles in a slot. This is a type error. ## Props [#props] [`VariantProps`](./typescript.mdx) on an extended function gives you the merged variants. ```ts import type { VariantProps } from 'emotion-variants'; type IconButtonVariants = VariantProps; // { // variant?: 'filled' | 'outlined' | 'text'; // size?: 'small' | 'medium' | 'large'; // color?: 'primary' | 'secondary'; // round?: true; // } ``` ## See also [#see-also] - [Slots](./slots.mdx) - [API Reference → extend](./ev.mdx#extend) # Responsive URL: https://emotion-variants.org/docs/responsive/ A variant often needs a different value at a different width: a small button on a phone, a large one on a desktop. `createEv` declares your breakpoints once, and every variant prop then accepts one value per breakpoint. ## Declare the breakpoints [#declare-the-breakpoints] Call `createEv` once and export the `ev` it returns. Import `ev` from this file instead of from `emotion-variants`. ```ts // ev.ts import { createEv } from 'emotion-variants'; export const { ev } = createEv({ breakpoints: { md: '@media (min-width: 768px)', lg: '@media (min-width: 1024px)', }, }); ``` Each key is a name you choose, and each value is the media query it stands for. List them from the smallest width to the largest. Configs stay the same. Nothing about a component's styles has to change. ```ts import { ev } from './ev'; const button = ev({ base: { border: '1px solid transparent', borderRadius: 8, cursor: 'pointer', fontWeight: 600, transition: 'all 0.2s ease', }, variants: { variant: { filled: { background: 'var(--button-color)', color: 'white', }, outlined: { background: 'transparent', borderColor: 'var(--button-color)', color: 'var(--button-color)', }, text: { background: 'transparent', color: 'var(--button-color)', }, }, size: { small: { padding: '8px 16px', fontSize: 12, }, medium: { padding: '10px 20px', fontSize: 14, }, large: { padding: '12px 24px', fontSize: 16, }, }, color: { primary: { '--button-color': '#d36ac2', }, secondary: { '--button-color': '#475569', }, }, }, defaultVariants: { variant: 'filled', size: 'medium', color: 'primary', }, }); ``` ## Pass a value per breakpoint [#pass-a-value-per-breakpoint] A variant prop takes either a value, as before, or an object keyed by `initial` and the breakpoint names. ```tsx ``` `initial` applies at every width, outside any media query. `md` puts the styles of `large` inside the `md` query, so they take over from 768px. The result is still an array of styles for the `css` prop. - A breakpoint you leave out adds nothing, so the one before it carries on. - When `initial` is left out, the axis's default variant takes its place. Without a default, the axis has no styles below the first breakpoint you pass. ```ts button({ size: { lg: 'large', }, }); // medium (the default) up to 1024px, large from there ``` ## In a component [#in-a-component] [`VariantProps`](./typescript.mdx) includes the responsive form, so forwarding the prop is enough. ```tsx import type { ComponentPropsWithoutRef } from 'react'; import type { VariantProps } from 'emotion-variants'; type ButtonProps = ComponentPropsWithoutRef<'button'> & VariantProps; function Button({ variant, size, color, ...rest }: ButtonProps) { return ``` ## Order [#order] Breakpoint styles are added in the order the breakpoints were declared, whatever the order of the keys you pass. That is why they are declared smallest first: when two queries match, the later one wins. In the stylesheet, a rule inside a media query comes after the rule that holds the plain styles. Inside its breakpoint, a breakpoint style therefore wins over every plain style for the same property, including one from an axis declared later and one from a compound variant. When two axes both set the same property inside media queries, the axis declared later wins wherever both queries match. ## Compound variants [#compound-variants] A compound variant needs one value per axis, and a responsive value is several. An axis that received a responsive value therefore matches no compound variant in that call. Compound variants that don't mention the axis still apply. ```ts button({ size: 'large', color: 'primary', }); // a compound on large + primary applies button({ size: { initial: 'large', }, color: 'primary', }); // it does not, but a compound on primary alone still does ``` This is true even when the object only has `initial`. Pass a plain value when there is just one. ## With slots [#with-slots] With [slots](./slots.mdx), the call and each slot function accept responsive values. A slot prop replaces the call's value for that axis as a whole. The two are not merged per breakpoint. ```ts const { root, title } = card({ size: { initial: 'small', md: 'large', }, }); root(); // small, large from md title({ size: 'small', }); // small at every width ``` ## Class names [#class-names] `className()` accepts responsive values, and the class it returns carries the media rules. ```ts button.className({ size: { initial: 'small', md: 'large', }, }); ``` `classNames` holds one class per variant value and has no entries for breakpoints. ## Rules [#rules] - `defaultVariants` takes single values. A responsive default is a type error. - `initial` is reserved, so it cannot be a breakpoint name. This is a type error. - A key that is not a declared breakpoint is a type error, and is ignored at runtime. - A breakpoint name must not look like a number, such as `'768'`. JavaScript moves such keys to the front of an object, so the order you declared is not kept. - The `ev` exported from `emotion-variants` has no breakpoints and accepts plain values only. - A function made by one `ev` can be [extended](./extending.mdx) by another. The breakpoints that apply are the ones of the `ev` that made the function you call. ## See also [#see-also] - [TypeScript](./typescript.mdx) - [API Reference → createEv](./create-ev.mdx) # TypeScript URL: https://emotion-variants.org/docs/typescript/ `emotion-variants` already infers variant types from your configuration. This page shows how to **derive React component props** from an `ev()` result so your component's prop types and styles stay in sync. ## The `VariantProps` type [#the-variantprops-type] `emotion-variants` exports `VariantProps`. Give it the type of any `ev()` result and it hands you the variants: ```ts import { ev, type VariantProps } from 'emotion-variants'; const button = ev({ variants: { size: { small: {}, medium: {}, large: {}, }, color: { primary: {}, danger: {}, }, }, }); type ButtonVariants = VariantProps; // { size?: 'small' | 'medium' | 'large'; color?: 'primary' | 'danger' } ``` Add a new value to `variants.size`, and `ButtonVariants['size']` updates automatically. ## Combining with HTML element props [#combining-with-html-element-props] For a polymorphic button-like component, intersect with `ComponentPropsWithoutRef`: ```tsx import type { ComponentPropsWithoutRef } from 'react'; export type ButtonProps = ComponentPropsWithoutRef<'button'> & ButtonVariants; export function Button({ size, color, ...rest }: ButtonProps) { return ; + return ; } ``` ```diff - function Button({ size = 'small' }: Props) { + function Button({ size }: Props) { return ; } ``` `false` and `0` are unaffected — they are real variant values and were never replaced by the default. ## The call always returns an array [#the-call-always-returns-an-array] v1 returned `Interpolation`, which was a bare `SerializedStyles` object when exactly one style matched. v2 always returns `SerializedStyles[]`. ```diff - (variants?: EvVariants): Interpolation; + (variants?: EvVariants): SerializedStyles[]; ``` The `css` prop accepts both, so `css={button(...)}` needs no change. Code that inspected the result does: ```diff - const styles = button({ size: 'large' }); - const list = Array.isArray(styles) ? styles : [styles]; + const list = button({ size: 'large' }); ``` ## `classNames` returns real class names [#classnames-returns-real-class-names] In v1 every entry was the string `"[object Object]"` — `String()` applied to a `SerializedStyles`. v2 injects each style through `@emotion/css` and returns the generated class. ```ts button.classNames.variants.size.small; // v1: '[object Object]' // v2: 'css-def456' ``` Nothing is injected until you first read `classNames`, and the result is memoized, so `css`-prop-only code pays nothing. If you worked around the old behavior by building class names yourself, delete that code. Note that `classNames` still covers `base` and single variant values only — for compound variants use [`className()`](./ev.mdx#classname). ## New: `className(variants)` [#new-classnamevariants] v2 adds a method returning one class for the whole combination, including compound variants. Useful for `className` props and non-React code. ```tsx ; ``` ## New: `EvClassNames` type [#new-evclassnames-type] `EvClassNames` is now exported. See [Types](./types.mdx). # ev URL: https://emotion-variants.org/docs/ev/ Creates a type-safe style function from a single configuration object. ```typescript const button = ev(config); ``` ## Usage [#usage] ### `ev(config)` [#ev-config] Use `ev` when a component has more than one visual axis — size, color, fill, state — and you want all of them declared in one place. It returns a function you call with variant values; the result goes straight to Emotion's `css` prop. ```typescript import { ev } from 'emotion-variants'; const button = ev({ base: { padding: '10px 20px', borderRadius: 8, cursor: 'pointer', }, variants: { size: { small: { fontSize: 12, }, large: { fontSize: 16, }, }, color: { primary: { background: 'blue', color: 'white', }, secondary: { background: 'gray', color: 'white', }, }, }, defaultVariants: { size: 'small', color: 'primary', }, }); ``` The configuration object is required. Pass `ev({})` if you have nothing to declare yet. #### Parameters [#parameters] - `config.base` (`CSSObject`): Styles applied on every call. Serialized once when `ev()` runs, not per call. - `config.variants` (`Record>`): The variant axes. Each axis maps a value to its styles. Because values are object keys, write Boolean and number values as keys — `true`, `false`, `1` — and they are typed back to `boolean` and number literals. - `config.compoundVariants` (`Array<{ variants, style }>`): Styles applied only when every listed variant value matches. A condition can also be an array of values, which matches any of them. Note the key is `style`, singular. - `config.defaultVariants` (`Partial>`): Values used when the caller omits an axis. - `config.slots` (`Record`): The parts of a multi-element component and their base styles. Replaces `base`, and keys every variant value and compound `style` by slot name. See [Slots](#slots). - `config.compoundSlots` (`Array<{ slots, variants?, style }>`): One style applied to several slots, always or only when `variants` match. Requires `slots`. - `config.extend` (`EvFunction | EvSlotsFunction`): Another `ev()` result to build on. Its styles, variants, compound variants, and default variants are inherited. See [extend](#extend). #### Returns [#returns] (`EvFunction`): A callable object. Call it to get styles, or read [`className()`](#classname), [`classNames`](#classnames), and [`variants()`](#variants) off it. With `config.slots` it is an `EvSlotsFunction` instead, described under [Slots](#slots). ### `button(variants)` [#call] Call the variant function to get the styles for one combination. Pass the result to the `css` prop or to Emotion's `css()`. ```tsx import type { ComponentPropsWithoutRef } from 'react'; import type { VariantProps } from 'emotion-variants'; type ButtonProps = ComponentPropsWithoutRef<'button'> & VariantProps; function Button({ size, color, ...rest }: ButtonProps) { return ``` Values are resolved per key with `??`, so an omitted or `undefined` value falls back to `defaultVariants`. That is what lets `Button` above forward its optional props straight through without guarding them. `false` and `0` are real values and are used as-is. `null` also falls back at runtime, but `EvVariants` does not include it — under `strictNullChecks`, `button({ size: null })` is a type error. Convert `null` to `undefined` before calling. ```typescript button({ size: undefined }); // identical to button() ``` An axis with neither a prop nor a default is skipped entirely. #### Parameters [#parameters-1] - `variants` (`EvVariants`, optional): Variant values. Every key is optional. With an `ev` from [`createEv`](./create-ev.mdx), a value can also be [responsive](./create-ev.mdx#responsive-values). #### Returns [#returns-1] (`SerializedStyles[]`): Always an array, even when a single style matches. Styles are ordered `base`, then matching `variants` entries in the order the axes were declared, then matching `compoundVariants` in array order. Later entries win on CSS conflicts, and the order of keys you pass in makes no difference. ### `button.className(variants)` [#classname] Use `className()` when you need a plain class string instead of the `css` prop — a non-React surface, a third-party component that only accepts `className`, or a test assertion. It merges `base`, the matching variants, **and** the matching compound variants into one class. ```tsx ; // defaultVariants apply exactly as they do for button(). button.className(); ``` #### Parameters [#parameters-2] - `variants` (`EvVariants`, optional): Variant values. Every key is optional. #### Returns [#returns-2] (`string`): One class name covering the whole combination. ### `button.classNames` [#classnames] A lookup table of the individual class names — one for `base` and one per variant value. Useful for composing with code that builds its own class lists, or for inspecting what was generated. ```typescript const button = ev({ base: { padding: 10, }, variants: { size: { small: { fontSize: 12, }, large: { fontSize: 16, }, }, outlined: { true: { border: '1px solid', }, }, level: { 1: { zIndex: 1, }, }, }, }); button.classNames.base; // 'css-abc123' button.classNames.variants.size.small; // 'css-def456' ``` Keys use the string form of the value, so Boolean and number axes are read as `true` and `1`: ```typescript button.classNames.variants.outlined.true; button.classNames.variants.level[1]; ``` Nothing is injected into the document until you first touch `classNames`, and the result is memoized — code that only uses the `css` prop pays nothing for it. ```typescript button.classNames === button.classNames; // true ``` `classNames` covers `base` and single variant values only. **Compound variants are not represented here** — there is no key for a combination. Use [`className()`](#classname) when compound styles matter. Concatenating these classes is not the same as calling the function. Each is a separate rule of equal specificity, so when `base` and a variant set the same property the winner is whichever Emotion inserted first, not the order you list them in. Use [`className()`](#classname) whenever a variant has to beat `base`. `base` is an empty string when the config has no `base`. #### Returns [#returns-3] (`EvClassNames`): `{ base, variants }`, where `variants[axis][value]` is a class name. ### `button.variants()` [#variants] Returns the axis names, in the order they were declared. Handy for building Storybook argTypes or a props table. ```typescript const button = ev({ variants: { size: { small: {}, large: {}, }, color: { primary: {}, secondary: {}, }, }, }); button.variants(); // ['size', 'color'] ``` A config without `variants` returns `[]`. #### Returns [#returns-4] (`Array>`): The axis names. The same array instance is returned on every call, so treat it as read-only. ### Slots [#slots] Declare `config.slots` instead of `config.base` when a component is made of several elements. Variant values and compound `style` are then keyed by slot name, and the call returns one style function per slot. ```tsx const card = ev({ slots: { root: { padding: 16, }, title: { fontWeight: 600, }, }, variants: { size: { small: {}, large: { root: { padding: 24, }, title: { fontSize: 20, }, }, }, }, compoundSlots: [ { slots: ['root', 'title'], style: { margin: 0, }, }, ], defaultVariants: { size: 'small', }, }); const { root, title } = card({ size: 'large', });

Title

; ``` Each slot function takes the same variants as the call. A value is resolved per axis from the slot's props, then the call's props, then `defaultVariants`, and compound entries are matched for each slot against the values it resolved to. Styles for a slot are ordered: its entry in `slots`, matching `variants` entries, matching `compoundVariants`, then matching `compoundSlots`. The rest of the object differs from the plain form in two places: - `card.className(variants)` returns one class name per slot, as `{ root: string, title: string }`. - There is no `card.classNames`. `card.variants()` is unchanged. `config.base` cannot be combined with `config.slots`, and only declared slot names are accepted wherever a slot is named. Both are type errors. #### Returns [#returns-5] (`EvSlotsFunction`): Calling it returns `{ [slot]: (slotVariants?) => SerializedStyles[] }`. See [Slots](./slots.mdx) for a walkthrough. ### extend [#extend] Pass another `ev()` result as `config.extend` to build on it. The new function inherits the parent's styles, variants, compound variants, and default variants. The parent is not changed. ```ts const button = ev({ base: { padding: '10px 20px', }, variants: { size: { small: { fontSize: 12, }, large: { fontSize: 16, }, }, }, defaultVariants: { size: 'small', }, }); const iconButton = ev({ extend: button, base: { display: 'inline-flex', }, variants: { size: { large: { width: 48, }, }, round: { true: { borderRadius: '50%', }, }, }, }); iconButton({ size: 'large', round: true, }); // padding, display, font-size, width, border-radius ``` The parent's styles come before the child's at every step, so the full order is: 1. `base`, parent then child 2. Matching `variants` entries, axis by axis; for each value, parent then child 3. Matching `compoundVariants` entries, parent then child Inherited axes keep their position and the child's new axes follow, which is also the order of `iconButton.variants()`. `defaultVariants` are merged per axis with the child's value winning. The child's `compoundVariants` and `defaultVariants` can refer to inherited axes and values. Every compound variant comes after every variant style, so a parent's compound variant still wins over a style the child declares for the same variant value. With [slots](#slots), the parent and the child must both be slot functions. The child's `slots` are added to the parent's, and a child without `slots` keeps the parent's. `compoundSlots` are inherited along with `compoundVariants`. `extend` throws when `ev()` runs in two cases: - The value is not an `ev()` result. If it did come from `ev()`, two copies of `emotion-variants` are probably installed. - A config with `slots` extends one without. This is a type error too, as is `config.base` on a child whose parent has `slots`. See [Extend](./extending.mdx) for a walkthrough. ## Try it out [#try-it-out] Edit the variant values and watch the button change. ## Types [#types] See [Types](./types.mdx) for `EvConfig`, `EvFunction`, `EvVariants`, and the rest of the exported type definitions. `className()` and `classNames` go through [`@emotion/css`](https://emotion.sh/docs/@emotion/css), which keeps its own global cache separate from `@emotion/react`. That means it ignores `CacheProvider` options such as `key` and `nonce`, and server rendering needs [`@emotion/server`](https://emotion.sh/docs/ssr#advanced-approach) to extract those styles. Avoid putting `css={button(...)}` and `className={button.className(...)}` on the same element. The two caches do not share an insertion order, so overrides may not resolve the way you expect. For server rendering this means two caches to extract, not one. Collecting only `@emotion/react`'s cache ships markup whose `className()` and `classNames` rules are missing, so the first paint is unstyled until hydration. # createEv URL: https://emotion-variants.org/docs/create-ev/ Creates an `ev` function whose variant props accept one value per breakpoint. ```typescript const { ev } = createEv(options); ``` ## Usage [#usage] ### `createEv(options)` [#create-ev-options] Use `createEv` when a variant should change with the width of the screen. Declare the breakpoints once, export the `ev` it returns, and use that `ev` across your app. ```typescript import { createEv } from 'emotion-variants'; export const { ev } = createEv({ breakpoints: { md: '@media (min-width: 768px)', lg: '@media (min-width: 1024px)', }, }); ``` #### Parameters [#parameters] - `options.breakpoints` (`Record`, optional): Media queries keyed by breakpoint name, from the smallest width to the largest. `initial` cannot be a name, and a name must not look like a number. #### Returns [#returns] (`{ ev: Ev }`): An object holding an `ev` function. It takes the same configuration as [`ev`](./ev.mdx), and the functions it returns accept [responsive values](#responsive-values). Without `breakpoints` it behaves like the `ev` exported from the package, which is `createEv().ev`. ### Responsive values [#responsive-values] Every variant prop of a function made by this `ev` takes a value, or an object with one value per breakpoint. ```typescript const button = ev({ variants: { size: { small: { fontSize: 12, }, large: { fontSize: 16, }, }, }, defaultVariants: { size: 'small', }, }); button({ size: { initial: 'small', md: 'large', }, }); ``` - `initial`: The value outside any media query. When omitted, the axis's default variant is used. - A breakpoint name: The value inside that breakpoint's media query. An omitted breakpoint adds nothing. The styles are added where the axis sits in the usual order: the `initial` styles first, then one style per breakpoint in the order the breakpoints were declared. A breakpoint style is serialized the first time its value is used and reused afterwards. An axis that received a responsive value matches no compound variant in that call, even when the object only has `initial`. `className()` and, with [slots](./ev.mdx#slots), each slot function accept the same values. `defaultVariants` does not. See [Responsive](./responsive.mdx) for the ordering rules and the limits. ## Types [#types] See [Types](./types.mdx) for `Ev`, `EvFunction`, and `EvVariants`, which carry the breakpoint names as their last type parameter. # Types URL: https://emotion-variants.org/docs/types/ Every type `emotion-variants` exports, and when you would reach for it. ```typescript import type { CompoundVariant, Ev, EvClassNames, EvConfig, EvFunction, EvSlotsFunction, EvVariants, VariantConfig, VariantKeys, VariantProps, VariantValue, VariantValueFor, } from 'emotion-variants'; ``` Most of the time you don't need any of them. Variant types are inferred from the configuration object, so reading props off the function you already have is shorter than naming the generic: ```typescript type ButtonVariants = VariantProps; ``` See [TypeScript](./typescript.mdx) for that pattern in full. ## Usage [#usage] ### `EvConfig` [#evconfigt-n-e] The shape of the object you pass to [`ev()`](./ev.mdx). Useful for extracting a configuration into its own variable or a factory. ```typescript import type { EvConfig } from 'emotion-variants'; const config: EvConfig<{ size: { small: { fontSize: number } } }> = { variants: { size: { small: { fontSize: 12, }, }, }, }; ``` Every field is optional: `base`, `variants`, `compoundVariants`, `defaultVariants`, [`extend`](./ev.mdx#extend), and for [slots](./ev.mdx#slots), `slots` and `compoundSlots`. `N` is the union of slot names. It defaults to `never`, which is the plain form without `slots`. `E` is the type of the `ev()` result passed as `extend`. It defaults to `undefined`, which is a config that extends nothing. ### `EvFunction` [#evfunctiont-b] The type of the value [`ev()`](./ev.mdx) returns — callable, plus `variants()`, `className()`, and `classNames`. ```typescript interface EvFunction { (variants?: EvVariants): SerializedStyles[]; variants: () => Array>; className: (variants?: EvVariants) => string; classNames: EvClassNames; } ``` `B` is the union of breakpoint names declared with [`createEv`](./create-ev.mdx). It defaults to `never`, which is a function that accepts plain values only. `EvSlotsFunction` and `EvVariants` take the same parameter. ### `EvSlotsFunction` [#evslotsfunctionn-t-b] The type [`ev()`](./ev.mdx#slots) returns when the configuration declares `slots`. `N` is the union of slot names. ```typescript interface EvSlotsFunction { (variants?: EvVariants): { [K in N]: (slotVariants?: EvVariants) => SerializedStyles[] }; variants: () => Array>; className: (variants?: EvVariants) => { [K in N]: string }; } ``` ### `Ev` [#evb] The type of the `ev` function itself. [`createEv`](./create-ev.mdx) returns an `Ev` whose results accept responsive values for the breakpoints `B`, and the `ev` exported from the package is an `Ev`. ```typescript import { createEv } from 'emotion-variants'; import type { Ev } from 'emotion-variants'; const { ev }: { ev: Ev<'md' | 'lg'> } = createEv({ breakpoints: { md: '@media (min-width: 768px)', lg: '@media (min-width: 1024px)', }, }); ``` ### `EvVariants` [#evvariantst-b] The argument type of the variant function: every axis, optional, narrowed to its declared values. This is what you want when writing a component's props by hand. ```typescript import type { EvVariants } from 'emotion-variants'; type Variants = EvVariants<{ size: { small: {}; large: {} }; }>; // { size?: 'small' | 'large' } // With breakpoint names, each value can also be given per breakpoint. type ResponsiveVariants = EvVariants< { size: { small: {}; large: {} }; }, 'md' | 'lg' >; // { size?: 'small' | 'large' | { initial?: 'small' | 'large'; md?: 'small' | 'large'; lg?: 'small' | 'large' } } ``` ### `VariantProps` [#variantpropst] The variant props an `ev()` result accepts. Pass it the type of the function, not the configuration. ```typescript import type { VariantProps } from 'emotion-variants'; type ButtonVariants = VariantProps; // { size?: 'small' | 'large'; color?: 'primary' | 'secondary' } ``` It resolves to the same type as `EvVariants` without you having to name `T` or `B`. ### `EvClassNames` [#evclassnamest] The shape of [`classNames`](./ev.mdx#classnames) — `base` plus a class name per variant value. Keys are the string form of each value. ```typescript type ClassNames = EvClassNames<{ outlined: { true: {}; false: {} }; }>; // { base: string; variants: { outlined: { true: string; false: string } } } ``` ### `CompoundVariant` [#compoundvariantt] One entry of `compoundVariants`. Reach for it when you build compound rules in a separate array. Each condition is a single value or [an array of values](./compound-variants.mdx#matching-several-values). ```typescript import type { CompoundVariant } from 'emotion-variants'; const variants = { size: { small: {}, large: {}, }, color: { primary: {}, danger: {}, }, }; const compounds: Array> = [ { variants: { size: 'large', color: 'primary', }, style: { fontWeight: 'bold', }, }, ]; ``` ### `VariantValue` [#variantvalue] The value types a variant axis accepts. ```typescript type VariantValue = string | number | boolean; ``` ### `VariantConfig` [#variantconfigt] The constraint applied to the `variants` field. You rarely write this yourself — it appears in the signature of `ev()` and in the other generic types. ### `VariantKeys` [#variantkeyst] The union of axis names in a variant configuration. ```typescript type Keys = VariantKeys<{ size: {}; color: {} }>; // 'size' | 'color' ``` ### `VariantValueFor` [#variantvaluefort-k] The valid values for one axis, mapped back from its style-object keys. String keys stay strings, `'true'` and `'false'` become `boolean`, numeric keys become number literals. ```typescript type Size = VariantValueFor<{ size: { small: {}; large: {} } }, 'size'>; // 'small' | 'large' type Outlined = VariantValueFor<{ outlined: { true: {}; false: {} } }, 'outlined'>; // boolean ``` ## Emotion types [#emotion-types] `CSSObject` and `SerializedStyles` come from `@emotion/react` and are not re-exported. Import them from Emotion directly when you need them. ```typescript import type { CSSObject, SerializedStyles } from '@emotion/react'; ``` # Changelog URL: https://emotion-variants.org/docs/changelog/ # emotion-variants ## 2.1.1 [#211] ### Patch Changes [#patch-changes] - [#56](https://github.com/JeongHwan-dev/emotion-variants/pull/56) [`821c511`](https://github.com/JeongHwan-dev/emotion-variants/commit/821c5114b5329edd1025762e1d27cd76ba3620e4) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - docs(core): refresh the README for slots, extend, and responsive variants, and link the new docs site at emotion-variants.org ## 2.1.0 [#210] ### Minor Changes [#minor-changes] - [#53](https://github.com/JeongHwan-dev/emotion-variants/pull/53) [`2e7f5b4`](https://github.com/JeongHwan-dev/emotion-variants/commit/2e7f5b41e637130a84c5c83e7dbc4714b734e6bb) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - feat(core): add `extend` to build one `ev()` result on another - `ev({ extend: button, ... })` inherits the parent's `base`, `variants`, `compoundVariants`, and `defaultVariants`; the parent is not changed - the parent's styles come before the child's at every step: `base`, then each matching variant value, then compound variants - a child can add values to an inherited axis, add styles to an inherited value, and declare new axes; `defaultVariants` are merged per axis with the child's value winning - with `slots`, a child can add slots and style inherited ones; a config with `slots` can only extend one with `slots` - `extend` throws at definition time when the value is not an `ev()` result, or when a config with `slots` extends one without - add a third type parameter to `EvConfig` for the type of the `extend` value (defaults to `undefined`) - [#54](https://github.com/JeongHwan-dev/emotion-variants/pull/54) [`36c2199`](https://github.com/JeongHwan-dev/emotion-variants/commit/36c2199ae2d18b8331288fd39b6cbf649e84ebcb) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - feat(core): add `createEv` for responsive variant values - `createEv({ breakpoints })` returns `{ ev }`; breakpoints are media queries keyed by a name, declared smallest first - every variant prop of that `ev` also accepts `{ initial, [breakpoint]: value }`; `initial` falls back to the default variant, and each breakpoint's styles are wrapped in its media query, in declared order - an axis that received a responsive value matches no compound variant in that call - `className()` and slot functions accept the same values; `defaultVariants` does not - the exported `ev` is `createEv().ev` and behaves as before - add the `Ev` type, and a trailing breakpoint-name parameter `B` (defaults to `never`) to `EvVariants`, `EvFunction`, and `EvSlotsFunction` - [#51](https://github.com/JeongHwan-dev/emotion-variants/pull/51) [`768ad08`](https://github.com/JeongHwan-dev/emotion-variants/commit/768ad08b66773b89461068353903bc67905d537b) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - feat(core): add `slots` and `compoundSlots` for multi-part components - `ev({ slots })` styles every part of a component from one config. Variant values and compound `style` are keyed by slot name, and the call returns one style function per slot: `const { root, title } = card({ size })`, then `css={root()}` - a slot function accepts the same variants as the call, resolved per axis as slot props, then call props, then `defaultVariants`; compound entries are matched per slot against the resolved values - `compoundSlots` applies one style to several slots, always or only when `variants` match - with `slots`, `className()` returns one class name per slot and there is no `classNames`; `base` cannot be combined with `slots` - export the `EvSlotsFunction` type, and add a second type parameter to `EvConfig` for the slot names (defaults to `never`) - `ReturnType>` no longer resolves to `SerializedStyles[]`, because `ev` now returns either form; use `SerializedStyles[]` from `@emotion/react` directly - [#50](https://github.com/JeongHwan-dev/emotion-variants/pull/50) [`83838ab`](https://github.com/JeongHwan-dev/emotion-variants/commit/83838abe785eb3525ee3d26d678fe236eba6a73d) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - feat(core): add the `VariantProps` type and array conditions in `compoundVariants` - export `VariantProps`, which extracts the variant props from an `ev()` result: `type ButtonVariants = VariantProps` - a `compoundVariants` condition can now be an array of values, which matches when the variant has any of them: `{ variants: { size: ['small', 'medium'] }, style }` - fix a variant value that only exists on `Object.prototype`, such as `'constructor'`, pushing a non-style value into the result; unknown values are now ignored ## 2.0.0 [#200] ### Major Changes [#major-changes] - [#43](https://github.com/JeongHwan-dev/emotion-variants/pull/43) [`3456f97`](https://github.com/JeongHwan-dev/emotion-variants/commit/3456f97b6273c4d918e2ce8315e1f056c58767a9) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - fix(core): apply default variants when a prop is `undefined`, make `classNames` return real class names - `button({ size: undefined })` now falls back to `defaultVariants.size` instead of dropping it; this matches the README `Button` example which forwards possibly-undefined props - `classNames` previously returned `"[object Object]"` for every entry because `@emotion/react`'s `css()` yields `SerializedStyles`, not class names. It now injects each style through `@emotion/css` on first access and returns the generated class names - add `className(variants)`, which returns one class name covering base, variant and compound variant styles, for `className` props and non-React code - `@emotion/css` is a new required peer dependency - `ev()` now always returns `SerializedStyles[]` (previously `Interpolation`, a bare object when only one style matched); the `css` prop accepts both ## 1.0.2 [#102] ### Patch Changes [#patch-changes-1] - [#41](https://github.com/JeongHwan-dev/emotion-variants/pull/41) [`176a7f2`](https://github.com/JeongHwan-dev/emotion-variants/commit/176a7f2c57e6d561a24d245261fad8fcf24a35d1) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - chore(core): switch to ESM package type and fix ESM type resolution - set "type": "module"; emit dist/index.{js,d.ts} for ESM and dist/index.{cjs,d.cts} for CJS - split exports "types" per import/require condition so node16 ESM no longer resolves CJS types - add "sideEffects": false, use git+https repository url, narrow "files" to dist - drop redundant react peer dependency (@emotion/react already declares it) - remove duplicate build from the release script (prepublishOnly already builds) - rename .lintstagedrc.js to .cjs, delete stale .npmignore, bump @types/node to 22 ## 1.0.1 [#101] ### Patch Changes [#patch-changes-2] - [#33](https://github.com/JeongHwan-dev/emotion-variants/pull/33) [`ddc21a5`](https://github.com/JeongHwan-dev/emotion-variants/commit/ddc21a54361ff8a0a25691e4f59f11ae4f89bb95) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - chore(core): build with tsdown instead of tsup Output filenames and entry points are unchanged; the bundle is 27-31% smaller gzipped. - [#27](https://github.com/JeongHwan-dev/emotion-variants/pull/27) [`ae2f98e`](https://github.com/JeongHwan-dev/emotion-variants/commit/ae2f98e706bab33eec4443769e06a12dea5fcc90) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - chore(core): remove unused `@emotion/serialize` runtime dependency - [#25](https://github.com/JeongHwan-dev/emotion-variants/pull/25) [`2630063`](https://github.com/JeongHwan-dev/emotion-variants/commit/26300636cf33e9186b19c376e0dfa0a9dc7e8e9c) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - ci(release): migrate release pipeline from semantic-release to changesets ## 1.0.0 [#100] ### Major Changes [#major-changes-1] - [`967258d`](https://github.com/JeongHwan-dev/emotion-variants/commit/967258df6562017bd60924a9f63a7bb617eba654) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **ev:** initial implementation of emotion-variants ### Patch Changes [#patch-changes-3] - [#10](https://github.com/JeongHwan-dev/emotion-variants/pull/10) [`c919712`](https://github.com/JeongHwan-dev/emotion-variants/commit/c91971282e5e2f76e67e322fdccec7d4531e45f3) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **cursor:** add emotion-variants library rules and update frontend guidelines - [#11](https://github.com/JeongHwan-dev/emotion-variants/pull/11) [`6482440`](https://github.com/JeongHwan-dev/emotion-variants/commit/6482440bae4f21d6666ba755df07b89edf8d5a6e) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **examples:** add design system example project - [#2](https://github.com/JeongHwan-dev/emotion-variants/pull/2) [`1aaa93a`](https://github.com/JeongHwan-dev/emotion-variants/commit/1aaa93a825039519d61a25c353f07ac0ce865a5c) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **github:** add pull request template to repository - [#9](https://github.com/JeongHwan-dev/emotion-variants/pull/9) [`1af7d81`](https://github.com/JeongHwan-dev/emotion-variants/commit/1af7d8108a97a8fd91e22d94d404919f24dccc7d) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **biome:** update biome version and clean up configuration - [#5](https://github.com/JeongHwan-dev/emotion-variants/pull/5) [`d157a3d`](https://github.com/JeongHwan-dev/emotion-variants/commit/d157a3d3af806fd0880a5f878f77262282537c20) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **commitizen:** add commitizen configuration - [#6](https://github.com/JeongHwan-dev/emotion-variants/pull/6) [`03f3da8`](https://github.com/JeongHwan-dev/emotion-variants/commit/03f3da8773ed2162afc9501d4a66ef933c0a8c16) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **commitizen:** improve commit message validation logic - [#8](https://github.com/JeongHwan-dev/emotion-variants/pull/8) [`2323bbd`](https://github.com/JeongHwan-dev/emotion-variants/commit/2323bbd567cce5556e6712a4f36a99d6880d3465) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **commitizen:** update commitizen config - [#14](https://github.com/JeongHwan-dev/emotion-variants/pull/14) [`f388a20`](https://github.com/JeongHwan-dev/emotion-variants/commit/f388a20c299996944a4df91aaa498f6af8449503) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **github:** update generate labels scripts and labels.json - [#7](https://github.com/JeongHwan-dev/emotion-variants/pull/7) [`b0d9000`](https://github.com/JeongHwan-dev/emotion-variants/commit/b0d9000b109119555bb7ae1c65d49e12a5529293) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **husky:** add husky for pre-commit and update scripts - [#1](https://github.com/JeongHwan-dev/emotion-variants/pull/1) [`2137060`](https://github.com/JeongHwan-dev/emotion-variants/commit/213706015976812b9d8bcbb5922d928516dc42fe) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **npmrc:** add .npmrc to ignore workspace root check - [#12](https://github.com/JeongHwan-dev/emotion-variants/pull/12) [`d6510b0`](https://github.com/JeongHwan-dev/emotion-variants/commit/d6510b010410ec883cc793745f5dab9301b39873) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **release:** configure semantic release with GitHub Actions - [#18](https://github.com/JeongHwan-dev/emotion-variants/pull/18) [`656c4a8`](https://github.com/JeongHwan-dev/emotion-variants/commit/656c4a87e08f90ad23b5bc297dedfbfcab5d5eac) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **release:** fix release workflow - [#19](https://github.com/JeongHwan-dev/emotion-variants/pull/19) [`76eefea`](https://github.com/JeongHwan-dev/emotion-variants/commit/76eefea731dce61fac28838a8bbb22e86eca422b) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **release:** fix release workflow - [#13](https://github.com/JeongHwan-dev/emotion-variants/pull/13) [`06e8467`](https://github.com/JeongHwan-dev/emotion-variants/commit/06e8467e2d1158e5ab2eb0f10313b71129be2345) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **release:** fix release workflow conditions and Node.js version - [#16](https://github.com/JeongHwan-dev/emotion-variants/pull/16) [`e8497a9`](https://github.com/JeongHwan-dev/emotion-variants/commit/e8497a9f851c4cb835dbc9cc2d625bbdea7d1829) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **release:** update release configuration and add release script - [#3](https://github.com/JeongHwan-dev/emotion-variants/pull/3) [`2488518`](https://github.com/JeongHwan-dev/emotion-variants/commit/248851831fff477f53a2810c48814b6380304b65) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **workflows:** add auto PR assignee workflow to assign repository owner - [#4](https://github.com/JeongHwan-dev/emotion-variants/pull/4) [`3373071`](https://github.com/JeongHwan-dev/emotion-variants/commit/337307185d1f55b6224711cdcde0e0850bc70729) Thanks [@JeongHwan-dev](https://github.com/JeongHwan-dev)! - **workflows:** add automated label generation files