Dynamic

A tiny (< 1kB compressed) runtime for performing dynamic updates to scoped theme variables.

npm install @vanilla-extract/dynamic

assignInlineVars

Allows variables to be assigned dynamically that have been created using vanilla-extract APIs, e.g. createVar, createTheme, etc.

As these APIs produce variable references that contain the CSS var function, e.g. var(--brandColor__8uideo0), it is necessary to remove the wrapping function when setting its value.

import { assignInlineVars } from '@vanilla-extract/dynamic';
import { container, brandColor } from './styles.css.ts';

// The following inline style becomes:
// { '--brandColor__8uideo0': 'pink' }

const MyComponent = () => (
  <section
    className={container}
    style={assignInlineVars({ [brandColor]: 'pink' })}
  >
    ...
  </section>
);

Even though this function returns an object of inline styles, it implements the toString method, returning a valid style attribute value so that it can be used in string templates.

app.ts
import { assignInlineVars } from '@vanilla-extract/dynamic'; import { container, brandColor } from './styles.css.ts'; // The following inline style becomes: // "--brandColor__8uideo0: pink;" document.write(` <section class="${container}" style="${assignInlineVars({ [brandColor]: 'pink' })}" > ... </section> `);

Assigning theme contracts dynamically

Theme contracts can also be assigned dynamically by passing one as the first argument. All variables must be assigned or it’s a type error.

This API makes the concept of dynamic theming much simpler.

import { assignInlineVars } from '@vanilla-extract/dynamic';
import { container, themeVars } from './theme.css.ts';

interface ContainerProps {
  brandColor: string;
  fontFamily: string;
}
const Container = ({
  brandColor,
  fontFamily
}: ContainerProps) => (
  <section
    className={container}
    style={assignInlineVars(themeVars, {
      color: { brand: brandColor },
      font: { body: fontFamily }
    })}
  >
    ...
  </section>
);

const App = () => (
  <Container brandColor="pink" fontFamily="Arial">
    ...
  </Container>
);

setElementVars

An imperative API, allowing variables created using vanilla-extract APIs, e.g. createVar, createTheme, etc, to be assigned dynamically on a DOM element.

import { setElementVars } from '@vanilla-extract/dynamic';
import { brandColor } from './styles.css.ts';

const el = document.getElementById('myElement');

setElementVars(el, {
  [brandColor]: 'pink'
});

Setting theme contracts dynamically

Theme contracts can also be set dynamically by passing one as the second argument. All variables must be assigned or it’s a type error.

import { setElementVars } from '@vanilla-extract/dynamic';
import { themeVars } from './theme.css.ts';

const el = document.getElementById('myElement');

setElementVars(el, themeVars, {
  color: { brand: 'pink' },
  font: { body: 'Arial' }
});