API

css.use / sx

★★★★★ Frozen

Attach styles as a prop in JSX, or as a class name string anywhere else.

Styles reach an element through the sx prop, or through css.use() where no prop is available.

sx

type Style = StyleList<StyleNamespace>;

declare global {
  namespace React {
    interface HTMLAttributes<T> {
      sx?: Style;
    }
    interface SVGAttributes<T> {
      sx?: Style;
    }
  }
}

export type { Style };

sx is the prop that applies styles to a JSX element. The plugin compiles it to className at build time.

Features

  • Accepts a single style, or an array of styles. Arrays can be nested.
  • Ignores false, null, and undefined wherever a style is accepted, which is what makes inline conditional branching work.
  • Within an array, a later style takes precedence over an earlier one.

Example

import * as css from '@plumeria/core';

const styles = css.create({
  base: { color: 'red' },
  active: { fontWeight: 'bold' }
});

function Component({ active }) {
  return (
    <div sx={[styles.base, active && styles.active]}>
      Hello
    </div>
  );
}

css.use()

export type use = (...rules: Style[]) => string;
export const use: use;

css.use() converts styles into a string of class names. Use it where the sx prop is not available, for example when passing a class name to an external component that only accepts className.

Pass every style to one css.use() call; a later argument takes precedence.

Each css.use() call is compiled separately. If results are joined and their styles set the same property, both classes reach the element and stylesheet order decides the winner:

import * as css from '@plumeria/core';

const styles = css.create({
  base: { padding: 24, color: 'green' },
  active: { padding: 8, color: 'teal' }
});

<ExternalComponent className={css.use(styles.base) + ' ' + css.use(styles.active)} />

Pass every Plumeria style to one call so the later argument wins:

<ExternalComponent className={css.use(styles.base, active && styles.active)} />

An external class name can still be joined, but overlapping properties follow the CSS cascade. The recommended @plumeria/no-unresolved-composition rule warns when a css.use() result is combined with another class name or passed to a helper such as clsx.

A function key cannot go through css.use(), and the build stops on it: its values reach the element as CSS variables on style, which a class name string cannot carry. Apply it with sx. A prop that ends up in css.use() can reject one at the call site with StaticStyles.

Example

import * as css from '@plumeria/core';

const styles = css.create({
  text: { fontSize: '16px' }
});

// Get the class name as a string
const className = css.use(styles.text);

// Apply to an external component
<ExternalComponent className={css.use(styles.text)} />

Compiled at build time

The plugin compiles both sx and css.use() at build time, so the bundle holds only the class name string.

Edit on GitHub